簡體   English   中英

特定數字和特殊字符的正則表達式

[英]Regex for specific numbers and special characters

我想從下面的輸入字符串中提取值 9.6%,2021,4th 並嘗試使用不同的解決方案,但沒有按預期顯示 output。 輸入字符串: 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); 

我提出的解決方案可能不是最佳解決方案,因為我認為它需要額外的步驟。

  1. 通過(\d+\.*\d*%)\s*in\s*(\d{4})\s*-\s*(1st|2nd|3rd|4th)得到想要的部分

  2. 由於您的問題存在細微差別,因此下一步有兩種可能性:

  • Replace() in and - to ,得到字符串"9.6%,2021,4th"
  • MatchGroup 1、2、3 組將是"9.6%""2021""4th"

問題是,處理文本總是有驚喜等着你。 測試更多情況並調整方法以處理異常輸入。

以供參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM