How to merge regex group matches?

后端 未结 1 1863
面向向阳花
面向向阳花 2020-12-11 17:21

Let\'s say I have the line below:

one two three

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

one three
<         


        
相关标签:
1条回答
  • 2020-12-11 17:59

    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.

    0 讨论(0)
提交回复
热议问题