0

I'm trying to greedy match string and mark it is as group until it encounter space dash ( -). So far I've got:

^ *-{2}([\w\d-]+)(=([ \w\d-]+))?(.*)|(.+)

and my test string is:

--match1=match2
--match1=match2 match2
--match1=match2 match2-match2
--mat-ch1=match2 match2
--match1=match2-match2 match2
--match1=match2 -lastmatch
--match1=match2 --lastmatch
--match1 -lastmatch
--match1 --lastmatch
lastormatch

Every each kind of match (match1, match2, lastmatch, lastormatch) should be grouped together if they are next to each other. This is working for every line, except 6 and 7. Basically '-' should act as delimiter when it comes to match2 group (but - surrounded by /w/d is fine as part of string inside group). I know, that lookahead/lookbehind should be used, but I can't get it right.

What I have comparing to what I need

regex101.com

a_z
  • 133
  • 1
  • 6

2 Answers2

0

Not entirely sure what you're trying to achieve, but based on your "what I need" picture this might be sufficient:

^ *-{2}([\w\d-]+)(=(?:[\w\d-]| (?!-))+)?(.*)|(.+)

By accepting either [\w\d-] or spaces not followed by - instead of [ \w\d-] it seems to work for you test data.

But without understanding exactly what your goal is there might be issues with a different data set.

rvalvik
  • 1,559
  • 11
  • 15
  • The idea is to recognise parameters that are passed to the bash script, since I don't want to use getopts. `^ *-{2}([\w\d-]+)(=((?:[\w\d-]| (?!-))+))?(.*)|(.+)` (one bracket more) worked exactly as I wanted. – a_z Mar 14 '17 at 14:44
  • @a_z Great! Glad you got it sorted. If you are looking to capture the different arguments then perhaps something along the lines of `(?:--?((?:[\w\d-]| (?!-))+)=?((?:[\w\d-]| (?![-]))+)?)|^([^-]+)$` could be relevant - https://regex101.com/r/NVgqNe/1 – rvalvik Mar 14 '17 at 15:12
  • Idea is to match first potential option +optional input (like `-v` or `--log-file=logfile`) convert it to `verbose=true` or `log_file=logfile` inside bash, shift initial match from input array and iterate trough rest of input array. I'm not quite done with interpreting single dash options (like -q or -qwer with optional input) just yet, but I'm getting there :). http://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash is a good post, but every answer is missing a bit or code is huge. – a_z Mar 14 '17 at 15:32
0

^ (?:--)([\w-]+)(?:=((?:[\w-]| \w)+))?|(.) Is exactly what I need. Combined answers of @trincot and @rvalvik.

a_z
  • 133
  • 1
  • 6