2017-02-27 992 views
2

在目标串词:This is a new pen.正则表达式 - 选择不完全或部分匹配

我的目标是把上面的字符串到This is a __ __.用JavaScript这样的:

const str = "This is a new pen." 
const newStr = str.replace(/[^this |is |a |an |the |are |.\s]+/ig, ' __ ').trim() 

可悲的是,正则表达式以上使用是错误的,因为它输出This is a ne __ __ en.因为“an”和“the”包含在正则表达式中。

我该如何达到目标,并且仍然在正则表达式中保留“an”和“the”?


编辑:

我修改了原始字符串 测试的anandthat's的效果,除了athisthe等:

const str = "This is a new pen and that's an old business book." 
const newStr = str.replace(/[^this |is |\'s |and |that |a |an |the |are |.\s]+/ig, ' __ ').trim() 

所以正则表达式现在比较长,但仍然存在问题。一个理想的结果应该是This is a __ __ and that's an __ __ __.

+0

这个正则表达式并没有做你期望的。方括号构成一个字符集;集合内字符的排序无关紧要。 – jasonharper

+0

@jasonharper我真的不擅长正则表达式。添加方括号是为了显示'^'**的效果,而不是**选择。 – sijane

+0

@sijane我已经大量更新了我的答案,现在完成了,我不知道你是否收到通知,但是你可能想要查看它。请告诉我,如果它不符合你对撇号的需求,我可能有一些时间来改进它,如果需要的话。 – Aaron

回答

3

对于一个更通用的解决方案,你会想从关键字数组制定一个正则表达式:

const keywordsList = ["this", "is", "his", ... ]; 
const pattern = new RegExp("\\b(?!(?:" + keywordsList.join("|") + ")\\b)\\w+", "gi"); 

const newStr = str.replace(pattern, '__').trim(); 

它工艺品形式(?!\b(?:word1|word2|word3)\b)\w+的正则表达式这匹配不是指定关键字之一的完整单词。

它可以很好地包裹在一个函数:

function hideWords(input, preservedWords, mask="__") { 
    const pattern = new RegExp("\\b(?!(?:" + preservedWords.join("|") + ")\\b)\\w+", "gi"); 
    return input.replace(pattern, mask); 
} 

取决于你想要做关于收缩的东西,它可以工作的开箱。因为好像你永远都不想让他们取代,只是收缩的每一部分添加到您的关键字列表(我假设你的文本不应该在其他情况下单独含有这些字母):

hideWords("This's what you'd've done!", ["this", "what", "you", "is", "his", "s", "d", "ve"]); 
// This's what you'd've __! 

hideWords("This is a new pen and that's an old business book.", ["this", "is", "s", "and", "that", "a", "an", "the", "are"]); 
// This is a __ __ and that's an __ __ __. 

它目前可以代替收缩的部分,但不与撇号,整个事情:

hideWords("This'll do.", ["this", "do"]); 
//This'__ do. 

hideWords("This'll do.", ["do"]); 
// __'__ do. 

如果不适合你,你至少需要的东西,包括'和返工更换正则表达式的\w部分字边界。由于我不确定这与您的兴趣有关,所以我暂时不打算对此进行研究。

+0

这将排除''s'因为它没有为我工作。 –

+0

@AbdulHameed可能不是,我没有看到编辑。感谢您通知我,我会尝试修复它:) – Aaron

+0

@AbdulHameed表明它配置为时,至少为OP的具体示例。 – Aaron

2

尝试这个正则表达式(?:(?!this |is |his |a |an |the |s |\s|\.).)+gi修饰符。

它列出你想不匹配(this--> this,his, is,s)

你可以找到演示here

UPDATE各种词的组合:

尝试新的正则表达式:

\b(?!this\b|is\b|a\b|and\b|that\b|the\b|\s|an\b|s\b|\').+?(?=\s|\.)

它不包括单词this,is,,a,and,that,the,an,',s并选择所有其他单词。

排除's我不得不再纠正一个负面看法,并消除它们。

你可以尝试完整的演示here

+0

它只能用于你的例子。不是每个案件。对于每种情况,我需要更多的正面和负面结果的测试用例来编写正则表达式 –

+0

感谢您的快速回复。只是我注意到了一个问题。如果目标字符串中有像“嘶嘶声”这样的单词,它们将显示部分内容而不是整个单词。除此之外,似乎我不能在正则表达式中添加像'|和'的相似性,因为字符串中的'和'将被部分替换。 – sijane

+0

在你的问题中列出更多的测试用例。那么只能获得解决方案。 –