Xregexp javascript optional named group seperated by white spaces

221 views Asked by At

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:

  • time : 1h 5m 1s

  • title : Title test

  • prize : Something random

1

There are 1 answers

0
Wiktor Stribiżew On BEST ANSWER

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

  • d(?:uration)?: - a d: or duration:
  • (?<time>.*?) - Group "time": any zero or more chars, as few as possible, up to the leftmost occurrence of the subsequent subpatterns
  • \s* - 0+ whitespaces
  • t(?:itle)?: - either title: or t:
  • (?<title>.*?)- Group "title": any zero or more chars, as few as possible
  • \s* - 0+ whitespaces
  • (?: - start of an optional non-capturing group matching 1 or 0 occurrences of:
    • p(?:rize)?: - p: or prize:
    • (?<prize>.*) - Group "prize": any zero or more chars, as few as possible
  • )? - end of the optional group
  • $ - end of string.