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
views:
36answers:
5Yep, a regex is probably overkill for this. If you **have** to use a regex, try `^[^"]*("[^"]*")*[^"]*$`
David
2010-08-12 12:16:40
@David: It’s rather `^[^"]*("[^"]*"[^"]*)*$`. Otherwise the quoted parts would be required to be immediately consecutive.
Gumbo
2010-08-12 13:01:15
A:
Even number of quotes ("
) is valid.
For example in Python:
def isvalid(mystring):
if mystring.count("\"")%2 == 0:
return True
return False
Ashish
2010-08-12 12:16:29
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
2010-08-12 12:33:18
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
2010-08-12 12:16:31
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
- regular-expressions.info/Anchors, Repetition
- Examples/Programming constructs/Strings - Has patterns for various strings
polygenelubricants
2010-08-12 12:17:28