I've been pulling my hair out over this, and I think I am quite close to actually getting it to work but I just can't seem to.
I've been attempting to pull out a specific substring from a string using Regex. This substring must match a certain set of strings/digits. Then after this, it should be returned to another function which will pull out the number only.
Here's some examples of strings that are present
"(DEV #198) I am a dev testing 23 different things."
"(dev #9540) I am a dev testing different other things."
"(FQ #1140) I am a dev testing different things."
"(fq #910) I am a dev testing different other things."
In the end I would like to have 198, 9540, 1140 or 910 as the final variable depending on the input.
Here is my Regex so far. I think it's close, but I need some help. (note the double backslashes for C#).
^(?=.*?\\b(dev|DEV|fq|FQ)\\b)(?=.*?\\b[0-9]{3,4}\\b).*$
Here is the fragment of code I'm using also.
string caseNumber = cpTicket.Desc;
string regexPattern = "^(?=.*?\\b(dev|DEV|fq|FQ)\\b)(?=.*?\\b[0-9]{3,4}\\b).*$";
caseNumber = Regex.Match(caseNumber, regexPattern).ToString();
That's as far as I have got with this. If you can help, I will be so grateful :D
Try the following expression:
(?<=(?:dev|fq) #)\d+
(?<=): This is a look behind to make sure the digits are preceded with what is inside the look behind.(?:dev|fq): This matches either dev or fq.#: Matches a space which is followed by a hash #.\d+: Matches one or more digits.Turn case insensitivity mode on so dev and fq could match in all cases.
You can turn case insensitivity from within the regular expression itself like this:
(?i)(?<=(?:dev|fq) #)\d+
In C#:
var input = "(DEV #198) I am a dev testing 23 different things.";
var matches = Regex.Matches(input, @"(?i)(?<=(?:dev|fq) #)\d+");
Notice how you can use the @ before the string to create what is called a verbatim string so you don't have to double escape everything.
I think you pattern can simply be:
"\(.*?\#(\d*)\)"
This will match the group in brackets and return the number.
var m = Regex.Match(input, @"\(.*?\#(\d*)\)");
if (m.Groups.Count > 0)
{
string matchedNumber = m.Groups[1].Value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With