从正则表达式开始并结束

时间:2014-07-23 09:56:34

标签: regex

我有下面列出的行。

remove product 100 unit replace with 200
Remove Product 100 unit Replace 200
Remove 100 unit Replace with a 200
remove product 100 unit replace with an 200
remove product2 100 unit replace with an 200

我试过下面的正则表达式,没有运气。

/([remove 100|remove Product 100](.*?)[replace with 200|replace with a 200|replace with an 200])/i

它应标记前四个结果,但不应标记为产品2。

它标记了regexr上的所有内容。示例可以在这里看到:http://regexr.com/396u3

任何帮助都会得到满足。

3 个答案:

答案 0 :(得分:1)

/remove (?:product )?100(.*?)replace (?:with )?(?:an? )?200/gi

上面的表达就足够了。

答案 1 :(得分:1)

你的正则表达式是,

^remove (?:product ?)?100 (\S+) (?:replace (?:with )?(?:an |a )?200)$

这将只捕获前4行中的字符串unit

DEMO

答案 2 :(得分:1)

您的问题是,您正在创建character class

[remove 100|remove Product 100]

而不是alternation

(remove 100|remove Product 100)

字符类只匹配方括号中字符之外的一个字符。因此,如果您将正则表达式更改为

/((remove 100|remove Product 100)(.*?)(replace with 200|replace with a 200|replace with an 200))/i

它会更好地匹配。