1

I would like to have a regex which accepts numeric along with specific special characters (.-,). I just learned about basics of regex and I don't know how come my pattern doesn't work, really need advice.

My Pattern

   ^(([0-9]*)+[.,\-]{0,1})$

(.,-) can only be repeated once, that's {0,1}. Also first should be numeric and last would also be numeric. I really need a little push.

Expected output

122-555-1521 //true

155--122 //false

155,- //false

.-12 //false

123.123. //false

.12 //false

1.2,1-3 //true
3
  • can you show us some expected outputs? Commented Jun 29, 2018 at 9:10
  • You can use: ^\d+(?:[.,-]\d+)*$ Commented Jun 29, 2018 at 9:15
  • (OT: {0,1} is shorter, and more commonly, written ?.) Commented Jun 29, 2018 at 9:15

2 Answers 2

3

You can use the simple pattern ^(?:\d+[.,-])*\d+$

  • several digits : \d+
  • one char from .,- : [.,-]
  • you can repeat the 2 previous elements : (?:\d[.,-])* ()?: non-capture for performance)
  • digits at the end : \d+
String[] array = {"122-555-1521", "155--122", "155,-", ".-12", "123.123."};
String pattern = "^(?:\\d+[.,-])*\\d+$";
for(String str : array){
    System.out.println(str+" "+str.matches(pattern));
}

122-555-1521 true
155--122     false
155,-        false
.-12         false
123.123.     false

Working Demo - Regex Demo

Sign up to request clarification or add additional context in comments.

9 Comments

'thanks for the answer with explanations of the patterns :) I;m very grateful thanks
Better to use: ^(?:\d+[.,-])*\d+$
@anubhava better for ? If you don't care about capture or not-capture no need of ?:
Better in terms of performance because ^(\d+[\.,-]?)*\d+$ backtracks and takes many times more steps to complete due to ? quantifier. Check this demo and see # of steps taken Using non-capture group and not escaping dot inside character class are just minor improvements.
can i ask what is the use of that ?: and capture and not-capture? is there a difference
|
1

If I understand correctly, you want to match groups of digits, separated by single non-digit characters from the set of [.,-]?

[0-9]+([.,\-][0-9]+)*

2 Comments

sorry i can't use this cause it also accepts spaces
You're right, I left out the ^ and $. However, azro's answer is more detailed and uses the more compact \d, so better than mine anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.