views:

36

answers:

5

Need a regular expression to validate a double quote(") is started and it must to be ended. Example : "This is valid" but "This is not valid

+1  A: 

You could just count the numbers of quotes. If it's even it's OK

schoetbi
Yep, a regex is probably overkill for this. If you **have** to use a regex, try `^[^"]*("[^"]*")*[^"]*$`
David
@David: It’s rather `^[^"]*("[^"]*"[^"]*)*$`. Otherwise the quoted parts would be required to be immediately consecutive.
Gumbo
A: 

If count of unescaped " is even then the string is valid

codaddict
A: 

Even number of quotes (") is valid.

For example in Python:

def isvalid(mystring):
    if mystring.count("\"")%2 == 0:
        return True
    return False
Ashish
Unless this is an academic problem (or a constraint we aren't aware of) you don't really need to use a regular expression here.
Ashish
A: 

What language? Wouldn't it be easyer to just take out the first and last character and check if it is the "-char?

Like this (in php):

$first = substr($string, 0, 1);
$last = substr($string, -1);
if ($first == """ && $last == """) {}

For RegEx it would be something like:

/^\"(*.)\"$/

Knarf
A: 

This pattern will work if no escaped doublequotes are allowed:

^"[^"]*"$

The ^ and $ are the beginning and end of the line anchors respectively.

The […] is a character class. Something like [aeiou] matches one of any of the lowercase vowels. [^…] is a negated character class. [^aeiou] matches one of anything but the lowercase vowels.

Thus the pattern validates that the entire line starts and ends with double quotes, and in between there are absolutely no doublequotes (but it could be empty).

See also

polygenelubricants