Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression that doesn't match when a certain character appears after another specific character?

Tags:

regex

I need a regular expression that does not match when a character exists in string after a specific character.

For example my first character is 'X' and the character that is no allowed after is 'U'.

Following is valid:

eUpXssseeeree // U is before X
rtsssXeeeree  // U is not there at all

Following is NOT valid

ereXUppsrrrsssss     // U is there right after X
ereeXrerrrtogUoosss  // U is still there even after a few characters

I'm using C# syntax. Can you guide me on how to write such a regular expression?

like image 360
AaA Avatar asked Oct 25 '25 04:10

AaA


2 Answers

Sounds like it could be as straightforward as "any characters, followed by X, followed by any characters that aren't U":

/^.*X[^U]*$/

(see reFiddle example)

Of course, you want to make sure to match the entire string by using start ^ and end $ characters.

like image 137
Wiseguy Avatar answered Oct 26 '25 17:10

Wiseguy


string testString = "eUpXssseeeree";

if ( !Regex.IsMatch( testString , @"[X].*[U]") )
{
     //Valid case
     //eUpXssseeeree // U is before X  
     //rtsssXeeeree  // U is not there at all
}
else
{
//Invalid Case
}
like image 21
gavin Avatar answered Oct 26 '25 17:10

gavin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!