Search code examples
regexregex-groupregex-greedy

How to capture two patterns (if exist) for two groups where string has quotes in regEx


I have different strings such as following.

$1"First title" asdas 
$2"Second title" 
$"This is post three title"
"This is post four title"
$5 the post
"hello \" world"

I want capture only strings that starts with "$" and attach to patterns of postid and posttitle if they exists. The format is: ${postid}"{posttitle}". So I want the match as below.

$1"First title" asdas (Should match: postid=1 and posttitle="First title")
$2"Second title" (Should match: postid=2 and posttitle="Second title")
$"Third title" (Should match: posttitle="Third title")
"This is post four title" (No match)
$5"" the post (Should match: postid=5)
$7 the post (No match)
$ asdasd (No match)
"hello \" world" (No match)

Currenly I end up with this regex:

%\$(?P<postid>\d+)"(?P<posttitle>.*?)"+%u

But it only matches $1"First title", $2"Second title", and $5"".


Solution

  • As you want either groups can be optional in your text, you need to use ? to make them appear zero or once. This regex should work for you,

    \$(?P<postid>\d+)?"(?P<posttitle>[^"]+)?"
    

    Live Demo