Pattern not surrounded by numbers or alphanumeric characters

I would like to find some words not surrounded by any numbers or alphanumeric characters or not surrounded by anything. So if I am looking for Foo123 I would like to get this result

="Foo123"; =>TRUE
barFoo123; =>FALSE
Foo123 =>TRUE
BarBar123Foo123Bar; =>FALSE
;Foo123 =>TRUE

      

I just built this expression:

(^[^0-9a-zA-Z]?)WORDTOFIND([^0-9a-zA-Z]?$)

      

I was sure I was right, but when I use it like this:

if (Regex.IsMatch(line, string.Format(@"(^[^0-9a-zA-Z]?){0}([^0-9a-zA-Z]?$)",snCode)) )
{   
}

      

This does not work. What am I doing wrong?

0


source to share


2 answers


You are mainly looking for

 (?<![a-zA-Z0-9])Foo123(?![a-zA-Z0-9])

      



This uses lookahead and lookbehind to make sure the alphanumeric character doesn't exist before or after Foo123

. This assumes ASCII.

+3


source


The following matches the lines you DO NOT want, so !Regex.IsMatch()



(^([0-9a-zA-Z])+{0}.*)|(.*{0}([0-9a-zA-Z])+)

      

0


source







All Articles