javascriptnode.jsregexexpressionxregexp

Xregexp javascript optional named group seperated by white spaces


I'm looking into an Xregexp expression that support named parameter preceded by letters . Here is my expression :

(?:d:|duration:)(?<time>.*\S+).*(?:t:|title:)(?<title>(?:.*\S+))(?:.*(?:(?:p:|prize:)(?<prize>.*\S+)))

It is working well, but the problem is I wanna put the p:<prize> group as optional, Which expression should I use ?

I'm also trying to end the capture when there is a white space

Example:

What I want :

duration:1h 5m 1s title:Title test [p:prize]<-optionnal group

I want to have the prize group as optional

Match with the current expression :

duration:1h 5m 1s title:Title test p:Something random

Group results:


Solution

  • You need to restrict your patterns a bit to get rid of .* that would eat up all up to the last occurrences of subsequent subpatterns. Then, use lazy dot pattern (.*?) whenever you need to match a value up to the next key, and add a $ (end of string) anchor at the end to make sure you will get all the text with the lazy dots.

    d(?:uration)?:(?<time>.*?)\s*t(?:itle)?:(?<title>.*?)\s*(?:p(?:rize)?:(?<prize>.*))?$
    

    See the regex pattern.

    Details