简体   繁体   中英

.NET regular expressions how to match a string that does not contain a word at a specific position

If I have a text line such as "so and so bit mike" where so and so could be any group of words with any group of spaces in it, what would a regular expression look like that would match

"so and so bit mike" but not "so and so really bit mike"

The only way I can think of to match so and so is .* , but .* (?!really)bit mike still matches.

Please note, for my purposes I need this to work with a single regex expression.

You might have used a negative lookahead ( (?!...) ) when you meant to use a negative lookbehind ( (?<!... ). The pattern:

(?<!really )bit mike

will match

so and so bit mike

but not

so and so really bit mike

.* (?!really)bit mike matches. in fact your negative lookahead is useless there because you're basically saying the next six characters must not be "really", but then you state that they must be "bit mi". No string can match "bit mi" and "really" at the same time so if:

.* bit mike matches a string then so does .* (?!really)bit mike

I don't know if this is the simplest way, but try using a negative lookbehind instead of a lookahead:

.*(?<!really) bit mike

Which says that the be six characters before bit mike which cannot be the string really

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