Question

I want to be able to capture a repeating group in a single line. I have done my work as shown below;

(((?:\s*^>\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[a-zA-Z]+\s*(,\s*[a-zA-Z]+\s*)*;$\s*)|(?:\s*^>\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[a-zA-Z]+\s*,\s*[0-9]+\s*(,\s*[\-]?[0-9]+\s*)*;$\s*))+)

Regular expression visualization

Edit live on Debuggex

It captures > 9, 2, door, open; and > 3, 3, door,1, 1; individually fine. However, I'd like to capture > 9, 2, door, close; > 1, 9, door, close; > 3, 3, door, 1, 1; as well. I enclosed my group by using parenthesis with + quantifier at the end, but it does not capture repeating pattern correctly. Could you show me where I did wrong?

EDITED

I made the regex somewhat shorter as follows;

(((\s*>\s*\d+\s*,\s*\d+\s*,\s*\w+\s*(,\s*\w+\s*)*;\s*)|(\s*>\s*\d+\s*,\s*\d+\s*,\s*\w+\s*,\s*\d+\s*(,\s*[\-]?\d+\s*)*;\s*))+)

Regular expression visualization

Was it helpful?

Solution

If you mean to write

> 9, 2, door, close; > 1, 9, door, close; > 3, 3, door, 1, 1;

in one line so you got to fix your regex by removing the ^ and $ totally so this will match

(((?:\s*>\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[a-zA-Z]+\s*(,\s*[a-zA-Z]+\s*)*;\s*)|(?:\s*>\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[a-zA-Z]+\s*,\s*[0-9]+\s*(,\s*[\-]?[0-9]+\s*)*;\s*))+)

In case you mean

> 9, 2, door, close;
> 1, 9, door, close;
> 3, 3, door, 1, 1;

so every one is in a separate line you got to fix your regex by adding the multiline ( /m or (?m) ) modifier so this will match

(?m)(((?:\s*^>\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[a-zA-Z]+\s*(,\s*[a-zA-Z]+\s*)*;$\s*)|(?:\s*^>\s*[0-9]+\s*,\s*[0-9]+\s*,\s*[a-zA-Z]+\s*,\s*[0-9]+\s*(,\s*[\-]?[0-9]+\s*)*;$\s*))+)

hope this solves your issue

OTHER TIPS

I'm sorry, your regex is waaaay too long for me to read... Instead of being smart and creating a small regex, if you want, you could just create a different one for each format and wrap all of those in parens and put pipes in between. For example, ((\d+)|([a-zA-Z]+))+

EDIT: you seem to be doing that. For the sake of ease, restart and just write each and every one individually first. Or, you can give more detail on your formats and we can write it for you :3

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top