Need a regular expression to validate started double quote is ended or not
Need a regular expression to validate a double quote(") is s开发者_如何学Pythontarted and it must to be ended.
Example : "This is valid" but "This is not validYou could just count the numbers of quotes. If it's even it's OK
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
If count of unescaped "
is even then the string is valid
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:
/^\"(*.)\"$/
Even number of quotes ("
) is valid.
For example in Python:
def isvalid(mystring):
if mystring.count("\"")%2 == 0:
return True
return False
精彩评论