正则表达式匹配直到某个字符的第一个实例 [英] Regex match until first instance of certain character
问题描述
我试图匹配一个 url 直到一个特殊字符,但是当我需要它在第一个实例之后停止时,我使用的正则表达式匹配最后一个实例.我做错了什么?!
I am trying to match a url up until a special character however the regex I am using is match the last instance when I need it to stop after the first instance. What am I doing wrong?!
.+?(?=\")
匹配所有内容直到第一个 "
To match everything until first "
但是我的结果如下:
推荐答案
您将 "
添加到模式的使用部分,将其删除.
You added the "
into the consuming part of the pattern, remove it.
^.+?(?=\")
或者,如果您需要匹配任何字符,包括换行符,请使用任一
Or, if you need to match any chars including line breaks, use either
(?s)^.+?(?=\")
^[\w\W]+?(?=\")
请参阅演示.这里,^
匹配字符串的开头,.+?
匹配任何 1+ 个字符,尽可能少,直到第一个 "
不包括它来自匹配,因为"是前瞻的一部分(零宽度断言).
See demo. Here, ^
matches start of string, .+?
matches any 1+ chars, as few as possible, up to the first "
excluding it from the match because the "` is a part of the lookahead (a zero-width assertion).
在另外两个正则表达式中,(?s)
使点匹配跨行,而 [\w\W]
是一种变通构造,可以匹配任何如果不支持 (s)
(或其 /s
形式),则为 char.
In the two other regexps, (?s)
makes the dot match across lines, and [\w\W]
is a work-around construct that matches any char if the (s)
(or its /s
form) is not supported.
最好使用否定字符类:
^[^"]+
查看另一个演示.这里,^[^"]+
从头开始匹配 1+ 个除 "
以外的字符(参见 [^"]+
)一个字符串 (^
).
See another demo. Here, ^[^"]+
matches 1+ chars other than "
(see [^"]+
) from the start of a string (^
).
这篇关于正则表达式匹配直到某个字符的第一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!