如何从正则表达式字符类中排除换行符?
给定这个 PCRE 模式:
/(<name>[^<>]*<\/name>[^<>]*<phone>[^<>]*<\/phone>)/
以及这个主题文本:
<name>John Stevens</name> <phone>888-555-1212</phone>
<name>Peter Wilson</name>
<phone>888-555-2424</phone>
如何让正则表达式匹配第一个姓名-电话对,但不匹配第二个?我不想匹配由换行符分隔的对。我尝试在否定字符类中包含行尾,例如 [^<>$]*
但没有任何改变。
您可以使用以下在线工具来测试您的表达:
http://rubular.com/
http://www.regextester.com/
谢谢。
Given this PCRE pattern:
/(<name>[^<>]*<\/name>[^<>]*<phone>[^<>]*<\/phone>)/
And this subject text:
<name>John Stevens</name> <phone>888-555-1212</phone>
<name>Peter Wilson</name>
<phone>888-555-2424</phone>
How can I get the Regular Expression to match the first name-phone pair but not the second? I don't want to match pairs that are separated by line breaks. I tried including an end-of-line in the negated character class like so [^<>$]*
but nothing changed.
You can use the following online tools to test your expressions:
http://rubular.com/
http://www.regextester.com/
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这样就可以了,
无论您在类
[ ]
中放入什么,都必须是代表单个字符的内容。$
在类中被解释为文字$
,可能是因为$
作为行尾是 0 宽度,并且不能在类中被解释为这样一堂课。 (在 ridgerunner 评论后编辑)顺便说一句,我去掉了正则表达式周围的括号,因为无论匹配什么,都可以称为整个匹配。
I think this will do it
Whatever you put in the class
[ ]
must be something that represents a single character.$
is interpreted as literal$
within a class, probably because$
as line end is 0-width, and could not be interpreted as such within a class. (Edited after comment by ridgerunner)By the way, I took off the parentheses that surrounds your regex because whatever matches it can be referred to as the whole match.
如果您不想匹配由换行符分隔的对,则以下正则表达式将完成这项工作:
仅匹配名字,电话对,因为点
.
不会匹配EOL
但[^<>]
将匹配它。在 http://rubular.com/r/amXvq20sl8 上进行了测试
If you don't want to match pairs separated by line breaks then following regex will do the job:
Matches only first name, phone pair since dot
.
will not matchEOL
but[^<>]
will match it.Tested it on http://rubular.com/r/amXvq20sl8
这些网站似乎不支持整个 PCRE 语法。我用过这个网站:
http://lumadis.be/regex/test_regex.php
这有效:
可能更好
Those sites don't seem to support the whole PCRE syntax. I used this site:
http://lumadis.be/regex/test_regex.php
And this worked:
is probably better