Reputation: 501
I need to search for a pattern within a string. For eg:
string big = "Hello there, I need information for ticket XYZ12345. I also submitted ticket ZYX54321. Please update.";
Now I need to extract/find/seek words based on the pattern XXX00000
i.e. 3 ALPHA and than 5 numeric.
Is there any way to do this ?
Even extraction will be okay for me.
Please help.
Upvotes: 0
Views: 265
Reputation: 11903
Here's a regex:
var str = "ABCD12345 ABC123456 ABC12345 XYZ98765";
foreach (Match m in Regex.Matches(str, @"(?<![A-Z])[A-Z]{3}[0-9]{5}(?![0-9])"))
Console.WriteLine(m.Value);
The extra bits are the zero-width negative look-behind ((?<![A-Z])
) and look-ahead ((?![0-9])
) expressions to make sure you don't capture extra numbers or letters. The above example only catches the third and fourth parts, but not the first and second. A simple [A-Z]{3}[0-9]{5}
catches at least the specified number of characters, or more.
Upvotes: 0
Reputation: 425
Use a regex:
string ticketNumber = string.Empty;
var match = Regex.Match(myString,@"[A-Za-z]{3}\d{5}");
if(match.Success)
{
ticketNumber = match.Value;
}
Upvotes: 0
Reputation: 756
You could always use a chatbot extension for the requests.
as for extracting the required information out of a sentence without any context you can use regex for that.
you can use http://rubular.com/ to test it, an example would be
...[0-9]
that would find XXX00000
hope that helped.
Upvotes: 0
Reputation: 3757
foreach (Match m in Regex.Matches(big, "([A-Za-z]{3}[0-9]{5})"))
{
if (m.Success)
{
m.Groups[1].Value // -- here is your match
}
}
Upvotes: 3
Reputation: 19820
You can use simple regular expression to match your following string
([A-Za-z]{3}[0-9]{5})
the full code will be:
string strRegex = @"([A-Za-z]{3}[0-9]{5})";
Regex myRegex = new Regex(strRegex, RegexOptions.IgnoreCase);
string strTargetString = @"Hello there, I need information for ticket XYZ12345. I also submitted ticket ZYX54321. Please update.";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
Upvotes: 0
Reputation: 10156
How about this one?
([XYZ]{3}[0-9]{5})
You can use Regex Tester to test your expressions.
Upvotes: 0