Regex C#. Match specific substring and return that substring only
c#, regex, string
Solution
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.
Problem
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