2

Sample

EL:123  
가나123.456다라  
123-ABC-456  
123.456+678.890  
AA03-BB1  
$.AB12,00

I want to extract any Number Format from String.

Number could be | 100,000 | 20,000.00 | 12.52 | 10,800.082 |

My pattern is

@"\d[\d|,|.]+"

But.. it does not work for just one digit | 3 | 1 |.

I also tried

@"[\d|,|.]+"

it should not catch | , | . | only.

What should I do to my regex pattern?

Uwe Keim
  • 36,867
  • 50
  • 163
  • 268
ibocon
  • 955
  • 3
  • 11
  • 31

1 Answers1

2

A \d[\d|,|.]+ regex will not find 3 or 1 because \d requires 1 digit, and the + with [\d|,|.]+ also requires at least one char more. Note this also matches 1| since the pipe symbol is considered a literal char in the character class. To match 0 or more occurrences, use * quantifier.

To match all those numbers, you may use either

 \d[\d,.]*

Or, better:

\d+(?:[,.]\d+)*

See the regex demo

Details:

  • \d+ - one or more digits
  • (?:[,.]\d+)* - zero or more (due to * quantifier) occurrences of:
    • [,.] - a comma or dot
    • \d+ - one or more digits
Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • Thank! is there any better resource to learn regular expression than MSDN page? – ibocon Nov 24 '16 at 10:26
  • I can suggest doing all lessons at [regexone.com](http://regexone.com/), reading through [regular-expressions.info](http://www.regular-expressions.info), [regex SO tag description](http://stackoverflow.com/tags/regex/info) (with many other links to great online resources), and the community SO post called [What does the regex mean](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean). Also, [rexegg.com](http://rexegg.com) is worth having a look at. For testing .NET regex patterns, I can recommend [Ultrapico Expresso](http://www.ultrapico.com/expresso.htm). – Wiktor Stribiżew Nov 24 '16 at 10:26