Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS regex match zero or more optional start with key words

Given string like keydown.capture.once.prevent.shift.control[arrowdown,arrowup]:silent I want to match shift.control[arrowdown,arrowup]:silent

And if the same keydown.capture.once.prevent.shift[arrowdown,arrowup]:silent then it should match shift[arrowdown,arrowup]:silent

Here the keywords shift | control are optional, ex: keydown.capture.once.prevent.[arrowdown,arrowup]:silent, matching string [arrowdown,arrowup]:silen

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I wrote the below regex, it can only capture zero or one keyword, but the expected result is zero or all keywords matching into separate group

(shift|control)?\[(.*?)\]:silent, how can we capture all the keywords if they exist?

Additional notes: Order of keywords doesn’t matter, ex it can be control.shift[]:silent

>Solution :

You may use any one of these regex solutions:

(?:(?:shift|control)\.?)*\[([^\]]*)\]:silent

This matches shift or control` optionally followed by a dit and repeats this non-capture group 0 or more times.

RegEx Demo

(?:shift(?:\.control)?|control(?:\.shift)?)?\[([^\]]*)\]:silent

This one matches shift.control OR control.shift in an optional non-capture group with the parts after dot optional in each alternation.

RegEx Demo 2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading