Regular expression is not matching new lines

2019-07-23 14:28发布

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?

2条回答
Bombasti
2楼-- · 2019-07-23 15:19

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

查看更多
疯言疯语
3楼-- · 2019-07-23 15:21

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.

查看更多
登录 后发表回答