简体   繁体   中英

Regex to take first set after Space and want to remove $ with same regex

My input string:-

" $440,765.12 12-108(e)\\n3 "

Output String i want as:-

"440,765.12"

I have tried with below regex and it's working but I am not able to remove $ with the same regex so anyone knows how to do the same task with below regex?

Regex rx = new Regex(@"^(.*? .*?) ");
var match = rx.Match(" $440,765.12  12-108(e)\n3 ");
var text = match.Groups[1].Value;

output after using above regex:- $440,765.12

I know I can do the same task using string.replace function but I want to do the same with regex only.

You may use

var result = Regex.Match(s, @"\$(\d[\d,.]*)")?.Groups[1].Value;

See the regex demo :

在此处输入图片说明

Details

  • \\$ - matches a $ char
  • (\\d[\\d,.]*) - captures into Group 1 ( $1 ) a digit and then any 0 or more digits, , or . chars.

If you want a more "precise" pattern (just in case the match may appear within some irrelevant dots or commas), you may use

\$(\d{1,3}(?:,\d{3})*(?:\.\d+)?)

See this regex demo . Here, \\d{1,3}(?:,\\d{3})*(?:\\.\\d+)? matches 1, 2 or 3 digits followed with 0 or more repetitions of , and 3 digits, followed with an optional sequence of a . char and 1 or more digits.

Also, if there can be any currency symol other than $ replace \\$ with \\p{Sc} Unicode category that matches any currency symbol:

\p{Sc}(\d{1,3}(?:,\d{3})*(?:\.\d+)?)

See yet another regex demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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