Regex match quoted string with spaces

965 views Asked by At

I'd like to find a regex that matches on characters surrounded by quotes that contains spaces within them

The examples trying:

adb shell am startservice -n fooApp/barService -a INVOKE --es "key" "key1" --es "value" "value 2 has spaces"

Would only match once on "value 2 has spaces"

So far I've got this

"([^"](?<=\s)[^"]*)"

But it's matching on " " between key" and "key1 and between value" and "value and " --es "...

I feel like I'm close but am missing something critical.

4

There are 4 answers

7
anubhava On

You can use this regex:

(?:"[^"\s]*"[^"]*)*("\S*\s[^"]*")

and grab captured group #1

RegEx Demo

0
Jahid On

You can use this regex:

"[^"\s]+[\s]+[^"]*"

Demo

If you want to make sure that "value.." has a preceding space i.e not matched "value ...", then use this one instead:

(?<=\s)"[\w]+[\s]+[\d\w\s]*"

Demo

0
Casimir et Hippolyte On

you can use this pattern and extract only non-empty values of the group 1:

"[^" ]*"|("[^"]*")
0
AudioBubble On

You can't validate the entire string for paired quotes.
The only thing you can do is to validate paired (balanced)
up to the quoted string you are looking for.

And you must force the engine to comply, ie. not skip ahead just to
find a match.

The only way you can force the engine to do that is to use the \G
anchor construct. It makes the engine match at the position where
the last match left off, or else it forces it to fail, to stop matching
entirely.

This will accomplish that -

\G[^"]*(?:"[^"\s]*"[^"]*)*("[^"\s]*\s[^"]*")

But, if the engine doesn't support the \G construct, some other way has
to be used.

 \G                # This MUST match where last match left off
 [^"]*             # Up to the next "
 (?:               # Absorb balanced, non space quotes
      " 
      [^"\s]* 
      " 
      [^"]* 
 )*
 (                 # (1 start), The quotes with spaces.
      "
      [^"\s]* 
      \s 
      [^"]* 
      " 
 )                 # (1 end)