Match returns empty string
c#, regex, string
Solution
You need to escape the key name, else, `(` and `)` are treated as grouping construct operators. This can be done with `Regex.Escape()` method.
Also, the `:(.+?)\n` part of the pattern requires a newline to be present. You need to just use a greedy quantifier version and remove `\n` since `.` matches any char but a newline in .NET regex:
$@"{Regex.Escape(fieldName)}:(.+)"
Here, `Regex.Escape()` will add literal backslashes in front of any special regex character, so that `(` could match a literal `(`, etc. The greedy quantifier will grab 1 or more non-newline chars at once, while the lazy one (`+?`) made the regex engine skip the quantified pattern and was trying to match a newline, which made the `\n` a required pattern part and made the pattern rather inefficient.
Note that in order to make `.` match any char but a newline, you should not pass the `RegexOptions.Singleline` option to the Regex constructor. If you can't control that, use a modifier group like this to make the `.` match non-newlines:
$@"{Regex.Escape(fieldName)}:((?-s:.+))"
^^^^^ ^
See an example `COMPANY PRICE \(INC VAT\):((?-s:.+))` regex demo on an online .NET regex tester.
Problem
I am using the following `Regex` to extract data from a string: ``` private static string ExtractRawString(string input, string fieldName) { return Regex.Match(input, $@"{fieldName}:(.+?)\n").Groups[1].Value; } ``` Where the input string is: ``` NAME OF PRODUCT: Product 30AMP \n \nCOMPANY PART NUMBER: 11111\nOEM COMPANY: COMPANY2 \n \nADD IMAGE HERE: \n \n \n \n - CHECKED \n \n \nOEM PART NUMBER: 22222 \nSERIAL NUMBER: 33333 \nCLASSIFICATION: Product \nDIMENSIONS: UNKNOWN \nWEIGHT: 0.06Kg’s \nCOMPANY PRICE (INC VAT): R 450.53 ZAR \nOEM PRICE: \nCoO: USA/MEXICO \n ``` For example, I could call the function like this: ``` var productName = ExtractRawString(inputString, "NAME OF PRODUCT"); ``` This works for every field in the input string (e.g. `NAME OF PRODUCT`, `COMPANY PART NUMBER`, etc.) aprt from `COMPANY PRICE (INC VAT)`. When I call the following, it just returns an empty string (`""`): ``` var companyPrice = ExtractRawString(inputString, "COMPANY PRICE (INC VAT)"); ``` I tried replacing `(.+?)` in the `Regex` with `(.)` but with the same result. Can anyone tell why this returns an empty string, when the format is the same as all the other fields?