Yegun kim Yegun kim - 11 days ago 5
C# Question

Advise for Regular Expression pattern needed

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?

Answer

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
Comments