简体   繁体   中英

C# regex string that is not another string

I want to match an at least 3 letter word, preceded by any character from class [-_ :] any amount of times, that is not this specific 3 letter word string2.

Ex: if string2="VER"

in

"    ODO VER7"
matched "    ODO"

or

"_::ATTPQ VER7"
matched "_::ATTPQ"

but if

" VER7"

it shoudn't match " VER"

so I thought about

Regex.Match(inputString, @"[-_:]*[A-Z]{3,}[^(VER)]", RegexOptions.IgnoreCase);

where

[-_:]* checks for any character in class, appearing 0 or more times

[AZ] the range of letters that could form the word

{3,} the minimum amount of letters to form the word

[^(VER)] the grouping construct that shouldn't appear

I believe however that [AZ]{3,} results in any letter at least 3 times (not what i want) and [^(VER)] not sure what it's doing

Using [^(VER)] means a negated character class where you would match any character except ( ) V E or R

For you example data, you could match 0+ spaces or tabs (or use \\s to also match a newline).

Then use a negative lookahead before matching 3 or more times AZ to assert what is on the right is not VER .

If that is the case, match 3 or more times AZ followed by a space and VER itself.

^[ \t]*[-_:]*(?!VER)[A-Z]{3,} VER

Regex demo

This would match the preceding class characters [-_ :] of 3 or more letters/numbers
that do not start with VER (as in the samples given) :

[-_ :]+(?!VER)[^\\W_]{3,}

https://regex101.com/r/wLw23I/1

^\\s*[-_:]*(?!VER)[AZ]{3,}

This regex asserts that between the start and end of the string, there's zero or more of your characters, followed by at least 3 letters. It uses a negative lookahead to make sure that VER (or whatever you want) is not present.

Demo

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