简体   繁体   中英

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].

My attempt is /opacity=([1-9][0-9]?|100)/ in Javascript . But it doesn't capture the 100.

Here is the link for debugging.

Put the 100 as the first alternative and move the ? quantifier to the [1-9] character class:

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

However , this regex also matches 20 in opacity=200 .

To make sure you only match 0 up to 100 , you should add a \\b word boundary:

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. However, the order of alternatives is irrelevant when using \\b as it requires the word boundary to appear after the number.

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.

Alternatively you could put the 100 in front of the 2 digit number

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

That way it still works greedy ( from left to right ) and searches for your 100 first. This is exactly the behaviour you want.

Try this

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

regex test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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