如何为字符串在 regEx 中包含引号的两个组捕获两个模式(如果存在)
How to capture two patterns (if exist) for two groups where string has quotes in regEx
我有不同的字符串,例如以下。
"First title" asdas
"Second title"
$"This is post three title"
"This is post four title"
the post
"hello \" world"
我只想捕获以“$”开头的字符串并附加到 postid 和 posttitle 的模式(如果它们存在)。
格式为:${postid}"{posttitle}"。所以我想要如下匹配。
"First title" asdas (Should match: postid=1 and posttitle="First title")
"Second title" (Should match: postid=2 and posttitle="Second title")
$"Third title" (Should match: posttitle="Third title")
"This is post four title" (No match)
"" the post (Should match: postid=5)
the post (No match)
$ asdasd (No match)
"hello \" world" (No match)
目前我得到这个正则表达式:
%$(?P<postid>\d+)"(?P<posttitle>.*?)"+%u
但它只匹配 $1"First title"、$2"Second title" 和 $5""。
由于您希望任一组在您的文本中都是可选的,因此您需要使用 ?
使它们出现零次或一次。这个正则表达式应该适合你,
$(?P<postid>\d+)?"(?P<posttitle>[^"]+)?"
我有不同的字符串,例如以下。
"First title" asdas
"Second title"
$"This is post three title"
"This is post four title"
the post
"hello \" world"
我只想捕获以“$”开头的字符串并附加到 postid 和 posttitle 的模式(如果它们存在)。 格式为:${postid}"{posttitle}"。所以我想要如下匹配。
"First title" asdas (Should match: postid=1 and posttitle="First title")
"Second title" (Should match: postid=2 and posttitle="Second title")
$"Third title" (Should match: posttitle="Third title")
"This is post four title" (No match)
"" the post (Should match: postid=5)
the post (No match)
$ asdasd (No match)
"hello \" world" (No match)
目前我得到这个正则表达式:
%$(?P<postid>\d+)"(?P<posttitle>.*?)"+%u
但它只匹配 $1"First title"、$2"Second title" 和 $5""。
由于您希望任一组在您的文本中都是可选的,因此您需要使用 ?
使它们出现零次或一次。这个正则表达式应该适合你,
$(?P<postid>\d+)?"(?P<posttitle>[^"]+)?"