I don't know how to get a second group given a string. Now I have Full Watch and Group 1(not completely) with (?:<p>)?@preview\\((.*)\\)(?:<\\/p>)?
Example strings:
@preview(example-component/example-component)
<p>@preview(example-component/example-component)</p>
@preview(example-component/example-component, title="sadad" text="asd")
@preview(example-component/example-component, title="sadad" text="asd" )
Full match:
@preview(example-component/example-component)
Or
<p>@preview(example-component/example-component)</p>
Or
@preview(example-component/example-component, title="sadad" text="asd")
Group 1:
example-component/example-component
Group 2:
title="sadad" text="asd"
Thanks
You could use
\(([^,)]+)(?:,\s*([^)]+))?
See a demo on regex101.com .
\\( # match a "(" literally ([^,)]+) # not a comma nor a ) -> group 1 (?:,\\s* # a non-capturing group, followed by whitespaces ([^)]+) # not a ) -> group 2 )? # thw whole term is optional
IN JavaScript
:
let strings = ['@preview(example-component/example-component)', '<p>@preview(example-component/example-component)</p>', '@preview(example-component/example-component, title="sadad" text="asd")', '@preview(example-component/example-component, title="sadad" text="asd" )']; let rx = /\\(([^,)]+)(?:,\\s*([^)]+))?/; strings.forEach(function(item) { let m = item.match(rx); if (typeof(m[2]) !== "undefined") { console.log(m[2]); } });
Your expression has only one matching group which matches everything inside the ()
, you just need to split it into 2 groups based on coma.
(?:<p>)?@preview\((.*?)(?:,\s*(.*?))?\)(?:<\/p>)?
I changed (.*)
to (.*?)(?:,\\s*(.*?))?
(.*?)
Non greedy all selector to match everything, non greedy makes it stop at the first coma it found
(?:,\\s*(.*?))?
Non capturing group to capture everything after the previous group including ,
to mark it as optional using ?
(.*?)
Second non greedy all selector captures everything after ,
excluding any spaces
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.