0

Using a regular expression, I would like to match the following string:

4232,2232

I have tried

^[0-9]+(,[0-9]+)$

However, it doesn't work as expected. I want to cater for 4 numbers, a comma and 4 numbers.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Scelo
  • 45
  • 2
  • 10

3 Answers3

10

You can use the following:

\d{4},\d{4}    //or ^\d{4},\d{4}$ with anchors for start and end of string

Explanation:

  • \d{4} match digits exactly 4 times (\d is shorthand notation for [0-9])
  • ,\d{4} followed by comma and exactly 4 digits again
karthik manchala
  • 13,492
  • 1
  • 31
  • 55
4

If i understand you correctly the RegEx you are looking for is basically:

(\d{4},\d{4})

This matches your provided expression as one group. As an alternative you could write:

([0-9]{4},[0-9]{4})

which has the same result.

FormigaNinja
  • 1,571
  • 1
  • 24
  • 36
Setch
  • 56
  • 5
1

In C#, you can use Regex.IsMatch with the \b\d{4},\d{4}\b regex:

var found_value1 = Regex.IsMatch("4232,2232", @"\b\d{4},\d{4}\b");
var found_value2 = Regex.IsMatch("12345,2232", @"\b\d{4},\d{4}\b");

\b makes sure we match whole number.

Output:

true
false
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563