开发者

Are there differences between "/\((.*)\)/" and "/\(([^\)]*)\)/"?

开发者 https://www.devze.com 2023-01-06 06:34 出处:网络
Are there differences开发者_开发问答 between /\\((.*)\\)/ and /\\(([^\\)]*)\\)/? In particular, would the second regular expression match a line ending, while the first one would not?Yes, AFAIK the do

Are there differences开发者_开发问答 between /\((.*)\)/ and /\(([^\)]*)\)/?

In particular, would the second regular expression match a line ending, while the first one would not?


Yes, AFAIK the dot does not match newlines in most regex engines without a modifier.

EDIT: Apparently JS doesn't even have that option. I personally think negated character classes are the way to go; I barely use the dot in regex.


Another important difference is that the dot will match ). Suppose you're you're trying to match the first parenthetical expression in

blah blah (foo) blah blah (bar)

The regex /\(.*\)/ will match (foo) blah blah (bar) because the * is greedy. You can fix that by using a reluctant quantifier instead - /\(.*?\)/ - but what if you want to match the last one? You know it's the last thing in the string, so you just add the end-of-string anchor - /\(.*?\)$/ - but now it's back to matching (foo) blah blah (bar) again. Only the negated character class will give you what you want in this case: /\([^)]*\)$/.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号