开发者

RegEx Problem: Invalid URL matches, but should not

开发者 https://www.devze.com 2023-02-14 00:39 出处:网络
I have the following string, which matches the following RegEx string. I would like it to not match. Test String: yahoo.c!om

I have the following string, which matches the following RegEx string. I would like it to not match.

Test String: yahoo.c!om

RegEx Pattern: 开发者_StackOverflow中文版[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?

Using an online tester, I can validate that "yahoo.c!om" matches. I can't figure out how modify the RegEx pattern to make it NOT match. Does anyone have any ideas? This RegEx stuff makes me want to jump off a building.


The . in regex matches any character (other than line breaks). So the . in:

[\w-_]+(.[\w-_]+)+([\w-.,@?^=%&:/~+#]*[\w-\@?^=%&/~+#])?
        ^
        ^
        ^

matches the ! from yahoo.c!om. Escape the . to match the literal . instead:

[\w-_]+(\.[\w-_]+)+([\w-.,@?^=%&:/~+#]*[\w-\@?^=%&/~+#])?
        ^^
        ^^
        ^^

That way, yahoo.c!om won't match entirely.

You may want to "anchor" your regex with the "start"- and "end-of-input" meta characters (^ and $ respectively):

^[\w-_]+(\.[\w-_]+)+([\w-.,@?^=%&:/~+#]*[\w-\@?^=%&/~+#])?$
0

精彩评论

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

关注公众号