Checking for multiple occurrence of character repeated or spread out in string with regex

10.7k Views Asked by At

Having syntax trouble, I'm new to using regex. I'm coding in java.

I need to check if an apostrophe is used more than once in a string. Multiple apostrophes can either be consecutive or spread out over the string.

For example: Doesn't'work or Can''t

I have an if statement, and I want it to evaluate to true if there is more than one apostrophe:

if(string.matches("\\'")){ 
.
.
}

any help would be great!

3

There are 3 best solutions below

16
On BEST ANSWER

I'm trying to use string.matches

IMHO you don't need it. You could just do this:

String s = "Doesn't'work or Can''t";

int lengthWithApostrophes = s.length();
int lengthWithoutApostrophes = s.replace("'", "").length();

if(lengthWithApostrophes - lengthWithoutApostrophes >= 2) {
    // Two or more apostrophes
}

If you want to do it with a regex, this is the first thing that came in my mind

s.matches(".*'.*'.*")
4
On
if(string.matches(".*\\\'.*\\\'.*")){ . . }
5
On

You don't need a regex for this. Since you are only looking for more than one occurrence, you can make use String#indexOf(String) and String#lastIndexOf(String) methods:

if (str.contains("'") && str.indexOf("'") != str.lastIndexOf("'")) {
    // There are more than one apostrophes
}