简体   繁体   English

正则表达式模式中的可选部分

[英]Optional part in regex pattern

I have following strings to process 我有以下字符串要处理

Name ( $4 USD )
Name ( $4.1 USD )
Name ( $4.12 USD )
Name ( $4123123.02 USD )

I want to USD amout from them Right now I a using follwoing regex pattern 我想从他们那里买单现在我正在使用正则表达式模式

Regex regex = new Regex(@"\( \$(?<cash>\d+\.\d{1,2}) USD \)");

but it does not match the first example. 但它与第一​​个示例不匹配。 What should I change to make the .\\d{1,2} part optional? 我应该更改些什么以使。\\ d {1,2}部分为可选? Thanks! 谢谢!

Regex regex = new Regex(@"\( \$(?<cash>\d+(?:\.\d{1,2})?) USD \)");

(?:...) is a non-capturing group, and the following ? (?:...)是一个非捕获组,以下内容是? makes that group optional. 使该组可选。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM