So, I am working on a program in which I need to check if a string has more than one dot. I went and looked at the documentation for regex
and found this:
X{n,m}? X, at least n but not more than m times
Following that logic I tried this:
mString = "He9.lo,"
if (myString.matches(".{1,2}?")){
System.out.print("it works");
}
But that does not works (It does not gives any error, it just wont do what is inside the if
). I think the problem is that is thinking that the dot means something else. I also looked at this question: regex but is for php and I don't know how to apply that to java.
EDIT: Basically I want to know if a string contains more than one dot, for example:
He......lo (True, contains more than one), hel.llo (False, contains one), ..hell.o (True Contains more than one).
Any help would be appreciated.
A dot in a regular expression means "any character". So if you want actual dots you need to escape it with a backslash - and then you need to escape the backslash within Java itself...
if (myString.matches("\\.{1,2}?")){
Next you need to understand that matches
tries to match the whole text - it's not just trying to find the pattern within the string.
It's not entirely clear what your requirements are - is it just "more than one dot together" or "more than one dot anywhere in the text"? If it's the latter, this should do it:
if (myString.matches(".*\\..*\\..*")) {
... in other words, anything, then a dot, then anything, then a dot, then anything - where the "anything" can be "nothing". So this will match "He..llo" and "H.e.llo", but not "He.llo".
Hopefully that's what you want. If you literally just want "it must have .. in it somewhere" then it's easier:
if (myString.contains(".."))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With