Home > Back-end >  C# regex matching on one or many digit(s) followed by a star but not when the full string is 05* and
C# regex matching on one or many digit(s) followed by a star but not when the full string is 05* and

Time:12-18

I'm trying to build a C# regex expression with these rules:

The last char has to be a *

The first char has to be a digit and can be followed by any number of digit but there must be at least 1 digit to start the string.

The complete string CAN'T be 05* or 07*

So these should match:

111*

12*

1*

Should NOT match on ONLY 05* 07*

This works for the match cases:

Regex oneOrManyDigitWithTrailingStar = new(@"\A\d [*]$", RegexOptions.Compiled);

This works to exclude 05* or 07*:

Regex IsNotZeroFiveStarOrZeroSevenStarOnly = new(@"(?s)(?<!\A05\*|\A07\*)$", RegexOptions.Compiled);

I've tried pretty much everything I could think of and read all the questions I could find to no avail. I can't seem to be able to combine both approach.

I hope someone can help.

CodePudding user response:

You can use

^(?!0[57]\*\z)[0-9] \*\z

Details:

  • ^ - start of string
  • (?!0[57]\*\z) - no 05*/07* allowed immediately to the right and up to the end of string
  • [0-9] - one or more ASCII digits
  • \* - a literal * char
  • \z - end of string.

See the .NET regex demo.

  • Related