0

Is it possible in JavaScript to find a nested match with an arbitrary regular expression (I found solutions only for spacial regex cases - not arbitrary)? For example, if I have the text "555666", and I try matching with the regex 5.*6 , I always get 1 match byt this code

let m = "555666".match(/5.*6/);

console.log(m)

but the desired output for me is get all matches

['56', '556', '5556', '566', '5666', ...]

Second example of regexp: a?.b|a.*c input string "aaabbbcaccdddedeee" and desired output

['ab', 'bb','aaabbbc',....]

I look for solution which works for arbitrary regexp - how I can do it in JS?

Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • 2
    Generate an array of all substrings of the string, and modify the regex to be `/^...$/`, then use [`.test()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) on each substring. – Patrick Roberts Jun 18 '19 at 20:57
  • 1
    Please be aware of [XY problem](http://xyproblem.info/): the task at hand might be solved using different methods, and forcing a regular expression into it is among the least optimal options. – rishat Jun 18 '19 at 21:03
  • *"get all matches"*: there are no multiple interpretations of a regex. In your example, 56 is not a valid match, because `.*` is greedy. – trincot Jun 18 '19 at 21:07
  • 1
    I have already answered this question. See [here](https://stackoverflow.com/a/34964708/3832970). Mark Reed [also provided a JS solution](https://stackoverflow.com/a/34965064/3832970). – Wiktor Stribiżew Jun 18 '19 at 21:09
  • 3
    I just posted an answer that allows lazy iteration of substring matches [here](https://stackoverflow.com/a/56657282/1541563). – Patrick Roberts Jun 18 '19 at 21:27
  • 2
    If you had branch reset `https://regex101.com/r/A5T2pB/1` –  Jun 18 '19 at 22:58

0 Answers0