简体   繁体   English

带前缀字符串的正则表达式匹配模式

[英]Regex match pattern with prefixed string

Here is my possible test string: (opacity=0) or (opacity=50) or (opacity=100) , the rules for opacity value must fall in [0, 100]. 这是我可能的测试字符串: (opacity=0)(opacity=50)(opacity=100) ,不透明度值的规则必须落在[0,100]中。

My attempt is /opacity=([1-9][0-9]?|100)/ in Javascript . 我的尝试是/opacity=([1-9][0-9]?|100)/Javascript But it doesn't capture the 100. 但是它并没有捕获到100。

Here is the link for debugging. 这是调试链接

Put the 100 as the first alternative and move the ? 将100作为第一个选择,并移动? quantifier to the [1-9] character class: [1-9]字符类的量词:

opacity=(100|[1-9]?[0-9])

However , this regex also matches 20 in opacity=200 . 但是 ,此正则表达式在opacity=200 也匹配 20

To make sure you only match 0 up to 100 , you should add a \\b word boundary: 为了确保您只匹配0到100 ,您应该添加\\b字边界:

opacity=(100|[1-9]?[0-9])\b
                         ^^

See another demo . 参见另一个演示

Note that 100 must be the first alternative in the group because it is a longer part than 0 or 18 , and it should be tested before any 1- or 2-digit number since the regex engine searches for matches from left to right. 请注意, 100必须是组中的第一个替代项,因为它是比018长的部分,并且应该在任何1或2位数字之前进行测试,因为正则表达式引擎从左到右搜索匹配项。 However, the order of alternatives is irrelevant when using \\b as it requires the word boundary to appear after the number. 但是,使用\\b时,替代顺序无关紧要,因为它要求单词边界出现在数字之后。

Your problem is, that the regex is greedy. 您的问题是,正则表达式是贪婪的。 Your first capture group with the 2 digits automatically grabs everything it can. 您的第一个具有两位数的捕获组将自动捕获所有可能的内容。 This behaviour is called "greedy". 此行为称为“贪婪”。

opacity=([1-9][0-9]?|100)\\b

One change could be to but a at the end of the regex. 除了正则表达式的末尾,还有一个更改。 \\b tells your regex-tester that the word/number ends here. \\b告诉您的正则表达式测试者,单词/数字在此结束。

Alternatively you could put the 100 in front of the 2 digit number 或者,您可以将100放在2位数的前面

opacity=(100|[1-9][0-9]?)\\b

That way it still works greedy ( from left to right ) and searches for your 100 first. 这样,它仍然可以从左到右贪婪地工作,并首先搜索100。 This is exactly the behaviour you want. 这正是您想要的行为。

Try this 尝试这个

opacity=(100|\d{1,2})

regex test 正则表达式测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM