简体   繁体   English

Java,正则表达式字符串不包含/之间的一组单词

[英]java, regex string not containing a set of word between /

I know this seems a common question, but can't get rid of my problem dispite searching. 我知道这似乎是一个常见的问题,但是尽管搜索也无法摆脱我的问题。 I need a regex that matchs only string that doesn't start with a specified set of words and surrounded by /. 我需要一个仅与不以指定的单词集开头且由/包围的字符串匹配的正则表达式。 Example: 例:

/harry/white
/sebastian/red
/tom/black
/tomas/green

I don't want strings starting with /harry/ and /tom/, so I expect 我不希望以/ harry /和/ tom /开头的字符串,所以我希望

/harry/white     NO
/sebastian/red   YES
/tom/black       NO
/tomas/green     YES

1) ^/(?!(harry|tom)).*    doesn't match /tomas/green
2) ^/(?!(harry|tom))/.*   matchs nothing
3) ^/((harry|tom))/.*     matchs the opposite

What is the right regex? 什么是正确的正则表达式? I'd appreciate much if someone explain me why 1 and 2 are wrong. 如果有人向我解释为什么1和2错误,我将不胜感激。 Please don't blame me :) Thanks. 请不要怪我:)谢谢。

You need to add the ending slash for both of them inside the negative look-ahead, not outside: 您需要在负前瞻而不是外部添加两个结尾的斜杠

^/(?!(harry|tom)/).*

Not adding a slash, will match tom in tomas , and the negative look-ahead will not satisfy. 不添加斜杠,将匹配tom中的tom ,并且负tomas将无法满足。

Try: 尝试:

^(?!/(harry|tom)/).*

Why number 1 is wrong: the lookahead should make sure that harry or tom are followed by a slash. 为什么数字1是错误的:前行应确保在harrytom后面加上斜杠。

Why number 2 is wrong: ignore the lookahead; 为什么数字2是错误的:忽略前瞻; note that the pattern is trying to match two slashes at the start of the string. 请注意,该模式试图在字符串的开头匹配两个斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM