wvp
wvp

Reputation: 1174

Regex to check if a single quote is preceeded by another single quote

I would like to write a regex to validate if a single quote is preceeded by another single quote.

Valid strings:

azerty''uiop
aze''rty''uiop
''azertyuiop
azerty''uiop''
azerty ''uiop''
azerty''''uiop
azerty''''uiop''''

Invalid strings:

azerty'uiop
aze'rty'uiop
'azertyuiop
azerty'uiop'
azerty 'uiop'
azerty'''uiop

Upvotes: 0

Views: 376

Answers (4)

Sazzadur Rahaman
Sazzadur Rahaman

Reputation: 7126

You can use the code bellow too:

str.matches("([^\']*(\'){2}[^\']*)+");

I think "([^\']*(\'){2}[^\']*)+" is easy to grasp, for the beginners. But this is not the best way to do this. It dies (runs into backtracking hell) when running for long input.

Upvotes: 0

fge
fge

Reputation: 121780

No need for a regex, just use .replace() to replace all sequences of two single quotes by nothing, then test whether you still find a single quote; if yes, the string is invalid:

if (input.replace("''", "").indexOf('\'') != -1)
    // Not valid!

If you also want to consider that strings with no single quotes are valid, you'll have to create a temporary variable:

public boolean isValid(final String input)
{
    final String s = input.replace("''", "");
    return s.equals(input) ? true : s.indexOf('\'') == -1;
}

Upvotes: 1

Paul Vargas
Paul Vargas

Reputation: 42040

Do you want a very fast solution? Try the next:

public static boolean isValid(String str) {
    char[] chars = str.toCharArray();
    int found = 0;
    for (int i = 0; i < chars.length; i++) {
        char c = chars[i];
        if (c == '\'') {
            found++;
        } else {
            if (found > 0 && found % 2 != 0) {
                return false;
            }
            found = 0;
        }
    }
    if (found > 0 && found % 2 != 0) {
        return false;
    }
    return true;
}

Upvotes: 0

nhahtdh
nhahtdh

Reputation: 56819

It can be done in one line:

inputString.matches("(?:[^']|'')*+");

The regex simply means, the string can contain 0 or more of

  • Non-quote character [^']
    OR
  • A pair of consecutive quotes ''

I used possessive version (*+) of 0 or more quantifier (*). Since it would be lengthy to explain what possessive quantifier means, I will refer you to here to learn about it. Simply put, it is an optimization.

Upvotes: 5

Related Questions