Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many dots are in a string. (Java)

Tags:

java

regex

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.

like image 562
0gravity Avatar asked Nov 29 '22 09:11

0gravity


1 Answers

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(".."))
like image 66
Jon Skeet Avatar answered Dec 17 '22 14:12

Jon Skeet