Home > Software design >  Match world if there is no special char - Regex using C#
Match world if there is no special char - Regex using C#

Time:03-04

How to match these string: Ks 1

I have used this pattern ^((?!\*).)*$!

Ks 1*, Zs 3v "6"
Ks 1 (/R)
Ks 1* Zs 3v "6"
Ks 1, (/R)*

The match that I want:

Ks 1 (/R)
Ks 1, (/R)*

CodePudding user response:

You can use

^(?!.*\d\*).*
^(?:(?!\d\*).)*$

See the .NET regex demo. Details:

  • ^ - start of string
  • (?!.*\d\*) - a negative lookahead that fails the match if, immediately to the right of the current location, there are any zero or more chars other than a newline char as many as possible and then a digit and a * char
  • (?:(?!\d\*).)* - a single char other than a newline char, zero or more but as many as possible occurrences, that does not start a digit * char sequence
  • .* - the rest of the line.
  • $ - end of string.

And if you plan to match Ks and a number after it that has no * right after, you can use

\bKs\s*\d \b(?!\*)

See the regex demo. Details:

  • \b - a word boundary
  • Ks - a string
  • \s* - zero or more whitespaces
  • \d - one or more digits
  • \b - a word boundary
  • (?!\*) - a negative lookahead that fails the match if there is a * immediately on the right.
  • Related