Regular expression is not matching new lines

北慕城南 提交于 2019-12-11 02:39:43

问题


I have the following reg ex:

"^((?!([\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3})))).)*$"

But it's not matching new lines as well:

https://regex101.com/r/nT6wK0/1

Any ideas how to make it match when there is a new line?


回答1:


The . at the and actually means

All but a line break character. (source)

By replacing it with [\S\s], it means

All spacing characters and all non-spacing characters; so all characters.

Then it seems to work. You could have used other variants like [\W\w], [\D\d],...

So the "correct" regex (please don't take my word for it, first test this) is:

^((?!([\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))))[\S\s])*$

regex101 demo.




回答2:


Assuming that you only want to match the first line, you can add the multiline option (/m) to include the newline.

If you want the second line to be included you'll need to read ahead an extra line. How you do that depends on the regex engine: N in sed; getline in awk; -n in perl; ...



来源:https://stackoverflow.com/questions/30362253/regular-expression-is-not-matching-new-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!