简体   繁体   中英

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

Try:

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

Why number 1 is wrong: the lookahead should make sure that harry or tom are followed by a slash.

Why number 2 is wrong: ignore the lookahead; note that the pattern is trying to match two slashes at the start of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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