Milad
Milad

Reputation: 5540

How to merge regex group matches?

Let's say I have the line below:

one two three

Is it possible to write a regex that would return below?

one three

I can of course get each part in a separate group but is it possible to capture that in a single match?

Upvotes: 13

Views: 10160

Answers (1)

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4874

To put it simply: no, it can't be done (as discussed in comments on your original question).

To find out why, let's look at it a bit more generally. A regular expression can be modelled as a (often complex) deterministic finite automaton, also known as a DFA, and your average regex engine is implemented as one. What this means is that the regex will slurp zero or one character at a time, and see if it matches the current token. If not, it will backtrack and attempt to match any possible token at the current stage (done with the alternation operation |). If unable, it halts and reports it cannot match. Since a DFA operates on the input in sequential order, what you're asking for is basically impossible by definition.

Upvotes: 6

Related Questions