[英]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.我想从下面的输入字符串中提取值 9.6%,2021,4th 并尝试使用不同的解决方案,但没有按预期显示 output。 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
输入字符串:
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);
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)
通过
(\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()
in
and -
to ,
to get string "9.6%,2021,4th"
Replace()
in
and -
to ,
得到字符串"9.6%,2021,4th"
Group
1,2,3 of the Match
will be "9.6%"
, "2021"
and "4th"
. Match
的Group
1、2、3 组将是"9.6%"
、 "2021"
和"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:以供参考:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.