'Regex for specific numbers and special characters
I want to extract the values 9.6%,2021,4th from the below input string and tried with different solutions but not displaying output as expected.
input string: Gross Domestic Product decreased by 5.9% in volume in the fourth quarter 2021 and by 9.6% in 2021 - 4th Quarter 2021
var pattren = "^-?\\d*(\\.\\d+)?$";
var result = Regex.Match(s, pattren);
Solution 1:[1]
A solution I came up, might not be optimal though, as it takes extra step I think.
Get the wanted part by
(\d+\.*\d*%)\s*in\s*(\d{4})\s*-\s*(1st|2nd|3rd|4th)Since there's a nuance in your question, there're 2 possibilities as the next step:
Replace()inand-to,to get string"9.6%,2021,4th"Group1,2,3 of theMatchwill be"9.6%","2021"and"4th".
Problem is, dealing with text always has surprises waiting for you. Test for more cases and adjust the method to deal with exceptional inputs.
For reference:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Xiang Wei Huang |
