Question

I need to check to see if a string of many words / letters / etc, contains only 1 set of triple double-quotes (i.e. """), but can also contain single double-quotes (") and double double-quotes (""), using a regex. Haven't had much success thus far.

Was it helpful?

Solution

A regex with negative lookahead can do it:

(?!.*"{3}.*"{3}).*"{3}.*

I tried it with these lines of java code:

String good = "hello \"\"\" hello \"\" hello ";
String bad = "hello \"\"\" hello \"\"\" hello ";
String regex = "(?!.*\"{3}.*\"{3}).*\"{3}.*";
System.out.println( good.matches( regex ) );
System.out.println( bad.matches( regex ) );

...with output:

true
false

OTHER TIPS

Try using the number of occurrences operator to match exactly three double-quotes.

  • \"{3}
  • ["]{3}
  • [\"]{3}

I've quickly checked using http://www.regextester.com/, seems to work fine.

How you correctly compile the regex in your language of choice may vary, though!

Depends on your language, but you should only need to match for three double quotes (e.g., /\"{3}/) and then count the matches to see if there is exactly one.

There are probably plenty of ways to do this, but a simple one is to merely look for multiple occurrences of triple quotes then invert the regular expression. Here's an example from Perl:

use strict;
use warnings;

my $match = 'hello """ hello "" hello';
my $no_match = 'hello """ hello """ hello';
my $regex = '[\"]{3}.*?[\"]{3}';

if ($match !~ /$regex/) {
    print "Matched as it should!\n";
}
if ($no_match !~ /$regex/) {
    print "You shouldn't see this!\n";
}

Which outputs:

Matched as it should!

Basically, you are telling it to find the thing you DON'T want, then inverting the truth. Hope that makes sense. Can help you convert the example to another language if you need help.

This may be a good start for you.

^(\"([^\"\n\\]|\\[abfnrtv?\"'\\0-7]|\\x[0-9a-fA-F])*\"|'([^'\n\\]|\\[abfnrtv?\"'\\0-7]|\\x[0-9a-fA-F])*'|\"\"\"((?!\"\"\")[^\\]|\\[abfnrtv?\"'\\0-7]|\\x[0-9a-fA-F])*\"\"\")$

See it in action at regex101.com.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top