Regex to match space after opening quotation mark

Viewed 149

I have written a regex to match sentences with quotation marks on both sides in a single line:
(?<!")"([^"\r]+)"(?!")

Input Text:
The sign said, "Walk." Then it said, "Don't Walk", then, "Walk", all within thirty seconds. He yelled, "Hurry up."

Match 1: "Walk."
Match 2: "Don't Walk"
Match 3: "Walk"
Match 4: "Hurry up."

Now, I want to have only matches which include a single space after opening quotation mark.

I tried to add (\ {1}) inside the regex after the first quotation. Now it looks like:
(?<!")"((\ {1})[^"\r]+)"(?!")

My new match is:
Match 1: " Then it said, "

But I expect no matches because there is no single space after quotation in any of my earlier 4 matches.

Now the whole thing is messed up because it ignores the initial structure and matches quotations independently which results in looking spaces even after closing quotation.

Any idea how to resolve this?

Thanks

3 Answers

The problem is that the double quote is your start and close delim char.

Use PCRE regex:

(?<!")"(?!\ )([^"\r]+)"(?!")(*SKIP)(*F)|(?<!")"\ ([^"\r]+)"(?!")

See proof. (?<!")"(?!\ )([^"\r]+)"(?!")(*SKIP)(*F) will match double quoted strings that does not have a space after the initial ", and will skip these matches. (?<!")"\ ([^"\r]+)"(?!") will fetch you the expected matches.

“Inside quotes” can be asserted by using a look ahead that requires the total number of quote chars that follow to be even:

" [^"]*"(?=(([^"]*"){2})*[^"]*$)

See live demo (I added a space in front of Don't walk to prove the regex does find quoted text starting with a space)

Note that you do not need to escape a space char, and a quantifier of {1} may be deleted without affecting the result.

If your objective is to obtain the text between successive double quotes when there is exactly one space after the opening quote, you could match the pattern:

(?<=") (?! )[^"\r\n]+(?=")

Start your engine!

If the space following the opening quote is not to be part of the string matched, change the regex to the following.

(?<=" )(?! )[^"\r\n]+(?=")
Related