Regex in Java matching specific special characters with number
Regex in Java matching specific special characters with number
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.
.,-
{0,1}
Expected output
122-555-1521 //true
155--122 //false
155,- //false
.-12 //false
123.123. //false
.12 //false
1.2,1-3 //true
You can use:
^d+(?:[.,-]d+)*$
– anubhava
Jun 29 at 9:15
^d+(?:[.,-]d+)*$
(OT:
{0,1}
is shorter, and more commonly, written ?
.)– Biffen
Jun 29 at 9:15
{0,1}
?
2 Answers
2
You can use the simple pattern ^(?:d+[.,-])*d+$
^(?:d+[.,-])*d+$
d+
.,-
[.,-]
(?:d[.,-])*
?:
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
'thanks for the answer with explanations of the patterns :) I;m very grateful thanks
– kenjiro jaucian
Jun 29 at 9:21
Better to use:
^(?:d+[.,-])*d+$
– anubhava
Jun 29 at 9:25
^(?:d+[.,-])*d+$
@anubhava better for ? If you don't care about capture or not-capture no need of
?:
– azro
Jun 29 at 9:26
?:
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.– anubhava
Jun 29 at 9:30
^(d+[.,-]?)*d+$
?
can i ask what is the use of that ?: and capture and not-capture? is there a difference
– kenjiro jaucian
Jun 29 at 9:32
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]+)*
sorry i can't use this cause it also accepts spaces
– kenjiro jaucian
Jun 29 at 9:31
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.
– WolfgangGroiss
Jun 29 at 9:53
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
can you show us some expected outputs?
– YCF_L
Jun 29 at 9:10