Jerrold
Jerrold

Reputation: 1564

Regular Expression (match word + some number) C#

Sorry doing this the fast way of asking all the regex experts out there :)

What regex for C# can I use that matches the end of a word + some number

Eg. End of string matches with "Story" + 0 or more numbers

"ThisIsStory1"    = true
"ThisIsStory2000" = true
"ThisIsStory"     = true
"Story1IsThis"    = false
"IsStoryThis1"    = false

Hope this makes sense

A regular expression that I could plug into C# would be fantastic.

Thanks

Upvotes: 5

Views: 33958

Answers (5)

drf
drf

Reputation: 8699

A .NET regex that meets your criteria is:

Story\d*\b

(Use the Regex.IgnoreCase option if desired.)

\b matches the word boundary, so Story1IsThis will not match, but ThisIsAStory1 will. The word 'Story' does not need to end the string, so the string "ThisIsAStory234 ThisIsNot" will match on Story234.

Upvotes: 0

TheVillageIdiot
TheVillageIdiot

Reputation: 40517

to match number of characters before story and then story???? use this:

"[A-Za-z]*(s|S)tory\d*$"

Upvotes: 1

f0ster
f0ster

Reputation: 558

string compare = "story1withANumber";
Regex regex = new Regex(@"[A-Za-z]+Story[0-9]*");

if (regex.IsMatch(compare))
{ 
    //true
}

regex = new Regex("[0-9]");

if (regex.IsMatch(compare))
{ 
    //true
}

Upvotes: 0

Ray
Ray

Reputation: 46595

You'll need something like this Story[0-9]*$

So it matches for story (ignoring anything before it, you may need to add more), then for 0 or more numbers between story and the end of the string.

Upvotes: 8

Cajunluke
Cajunluke

Reputation: 3113

Try [A-Za-z]*Story[0-9]*.

If you want to check against a whole line, ^[A-Za-z]*Story[0-9]*$.

Upvotes: 2

Related Questions