Nikola R.
Nikola R.

Reputation: 1173

Regex - Get string between quotes even if it's empty

To get "Testing if \"quotes\" are working." from this string:
msgid "Testing if \"quotes\" are working.", I am using this pattern:

~msgid(?:\s*)(\"[^\"](?:\\.|[^\"])*\")~m

However, it fails if I have msgid ""

How can I extract string even if it's empty?

Upvotes: 3

Views: 1757

Answers (2)

bobble bubble
bobble bubble

Reputation: 18555

You can further use this more efficient technique to reduce backtracking.

msgid\s*("(?:[^\\"]*\\.)*[^\\"]*")

(this will also match, if there is nothing inside the double quotes)

See demo at regex101


Depending on how you use the pattern, it might be necessary to further escape backslashes eg PHP:

$re = '/msgid\s*("(?:[^\\\"]*\\\.)*[^\\\"]*")/';

See demo at eval.in

Upvotes: 1

Jan
Jan

Reputation: 43199

It is because the construct [] always requires at least one character, which it does not find when the string is empty. An easy solution would be to make it optional (add ?):

~msgid(?:\s*)(\"[^\"]?(?:\\.|[^\"])*\")~m

See a demo here on regex101.com.

Upvotes: 5

Related Questions