meds
meds

Reputation: 22926

Looking for patterns in a string how to?

I'm trying to find all instances of the substring EnemyType('XXXX') where XXXX is an arbitrary string and the instasnce of EnemyType('XXXX') can appear multiple times.

Right now I'm using a consortium of index of/substring functions in C# but would like to know if there's a cleaner way of doing it?

Upvotes: 3

Views: 78

Answers (1)

jetstream96
jetstream96

Reputation: 146

Use regex. Example:

using System.Text.RegularExpressions;

var inputString = "   EnemyType('1234')abcdeEnemyType('5678')xyz";
var regex = new Regex(@"EnemyType\('\d{4}'\)");

var matches = regex.Matches(inputString);

foreach (Match i in matches)
{
    Console.WriteLine(i.Value);
}

It will print:

EnemyType('1234')
EnemyType('5678')

The pattern to match is @"EnemyType\('\d{4}'\)", where \d{4} means 4 numeric characters (0-9). The parentheses are escaped with backslash.

Edit: Since you only want the string inside quotes, not the whole string, you can use named groups instead.

var inputString = "   EnemyType('1234')abcdeEnemyType('5678')xyz";
var regex = new Regex(@"EnemyType\('(?<id>[^']+)'\)");

var matches = regex.Matches(inputString);

foreach (Match i in matches)
{
    Console.WriteLine(i.Groups["id"].Value);
}

Now it prints:

1234
5678

Regex is a really nice tool for parsing strings. If you often parse strings, regex can make life so much easier.

Upvotes: 3

Related Questions