Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a specific sentence with Regex

Tags:

c#

.net

regex

I'm new to Regex and I couldn't cope with matching this sort of sentence: Band Name @Venue 30 450, where the digits at the end represent price and quantity.

string input = "Band Name @City 25 3500";
Match m = Regex.Match(input, @"^[A-Za-z]+\s+[A-Za-z]+\s+[\d+]+\s+[\d+]$");
if (m.Success)
{
    Console.WriteLine("Success!");
}
like image 738
Shrexpecial Avatar asked Sep 17 '25 10:09

Shrexpecial


1 Answers

You can use Regex and leverage usage of named groups. This will make easier to extract data later if you need them. Example is:

string pattern = @"(Band) (?<Band>[A-Za-z ]+) (?<City>@[A-Za-z ]+) (?<Price>\d+) (?<Quantity>\d+)";
string input = "Band Name @City 25 3500";

Match match = Regex.Match(input, pattern);

Console.WriteLine(match.Groups["Band"].Value);
Console.WriteLine(match.Groups["City"].Value.TrimStart('@'));
Console.WriteLine(match.Groups["Price"].Value);
Console.WriteLine(match.Groups["Quantity"].Value);

If you looked at the pattern there are few regex groups which are named ?<GroupName>. It is just a basic example which can be tweaked as well to fulfill you actual needs.

like image 113
Johnny Avatar answered Sep 20 '25 00:09

Johnny