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!");
}
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.
Here is a very old and elaborated way : 1st way
string re1=".*?"; // Here the part before @
string re2="(@)"; // Any Single Character 1
string re3="((?:[a-z][a-z]+))"; // Word 1, here city
string re4="(\\s+)"; // White Space 1
string re5="(\\d+)"; // Integer Number 1, here 25
string re6="(\\s+)"; // White Space 2
string re7="(\\d+)"; // Integer Number 2, here 3500
Regex r = new Regex(re1+re2+re3+re4+re5+re6+re7,RegexOptions.IgnoreCase|RegexOptions.Singleline);
Match m = r.Match(txt);
if (m.Success)
{
String c1=m.Groups[1].ToString();
String word1=m.Groups[2].ToString();
String ws1=m.Groups[3].ToString();
String int1=m.Groups[4].ToString();
String ws2=m.Groups[5].ToString();
String int2=m.Groups[6].ToString();
Console.Write("("+c1.ToString()+")"+"("+word1.ToString()+")"+"("+ws1.ToString()+")"+"("+int1.ToString()+")"+"("+ws2.ToString()+")"+"("+int2.ToString()+")"+"\n");
}
In the above way you can store the specific values at a time . Like in your group[6] there is 3500 or what value in this format.
you can create your own regex here : Regex
And in a short, others given answers are right. 2nd way just create the regex with
"([A-Za-z ]+) ([A-Za-z ]+) @([A-Za-z ]+) (\d+) (\d+)"
And match with any string format. you can create you won regex and test here: Regex Tester
This one should work:
[A-Za-z ]+ [A-Za-z ]+ @[A-Za-z ]+ \d+ \d+
With your code it'd be:
string input = "Band Name @City 25 3500";
Match m = Regex.Match(input, "[A-Za-z ]+ [A-Za-z ]+ @[A-Za-z ]+ \d+ \d+");
if (m.Success)
{
Console.WriteLine("Success!");
}
That is the answer to what I was trying to do:
string input = "Band Name @Location 25 3500";
Match m = Regex.Match(input, @"([A-Za-z ]+) (@[A-Za-z ]+) (\d+) (\d+)");
if (m.Success)
{
Console.WriteLine("Success!");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.