Regex for Number (or) Number and Comma (or) Number Comma and Space (or) Number Comma Space Number

Viewed 53

I am new to regex learning and I am trying to achieve the below. I will be really thankful to anyone who can help me in my learning

What I'm trying to achieve Number (or) Number and Comma (or) Number Comma and Space (or) Number Comma Space Number

My Regex: (^\d$)|(^\d,+$)|(^\d\s+$)|(^\d,\s)+$|(^\d,+\d)$

Complete Test Data URL : https://regexr.com/5eogj

Pass Data

  • 11
  • 11,11
  • 1, 111,11
  • 111,,,
  • 11, [whitespace]
  • 1 , 1

Fail/Invalid Data

  • ABC
  • Any Special Characters other than comma and space
  • 111 1111
1 Answers

You can use

^\s*\d+(?:\s*,+\s*\d*)*\s*$

See the regex tests at regexr.

When you use it in Java to validate your input strings, use

str.matches("\\s*\\d+(?:\\s*,+\\s*\\d*)*\\s*")

Details

  • ^ - start of string
  • \s* - 0+ whitespaces
  • \d+ - 1+ digits
  • (?:\s*,+\s*\d*)* - zero or more repetitions of
    • \s* - 0+ whitespaces
    • ,+ - one or more commas
    • \s* - 0+ whitespaces
    • \d* - zero or more digits
  • \s* - 0+ whitespaces
  • $ - end of string.
Related