Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for patterns in a string how to?

Tags:

string

c#

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?

like image 446
meds Avatar asked Feb 20 '26 22:02

meds


1 Answers

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.

like image 137
jetstream96 Avatar answered Feb 23 '26 12:02

jetstream96