0

Say I have the following string:

var str1 = "62y^2";

and I want the following result:

[62,y,^2]

Now when I tried the below regex I didn't get the desired result:

str.match(/(\d*)|([a-zA-Z]*)|(\^[a-zA-Z\d]*)/g)

But when I try the below regex:

str.match(/\^(\d+|[a-zA-Z]+)|[a-zA-Z]+|\d+/g);

I get the desired result, why is my first regex not working? Is it because of the capture groups? I am not so well versed in regexs.

halfer
  • 19,824
  • 17
  • 99
  • 186
Alexander Solonik
  • 9,838
  • 18
  • 76
  • 174
  • You did not use `g` modifier with the first regex, so you only got the first match. – Wiktor Stribiżew Feb 08 '18 at 09:11
  • Furthermore, you use `*` as quantifier in one and `+` in the other. – Sebastian Proske Feb 08 '18 at 09:13
  • @WiktorStribiżew even with the g modifier i dont' get the desired result I.E. `[62,y,^2]` – Alexander Solonik Feb 08 '18 at 09:14
  • @AlexanderSolonik You did not move the regex lastIndex then. If you did, it would work even with `*`. Surely, `+` is what you need to match 1+ occurrences. – Wiktor Stribiżew Feb 08 '18 at 09:15
  • @WiktorStribiżew yes you are right with the `+` operator , works fine. But why with `*` , i don't get the same result – Alexander Solonik Feb 08 '18 at 09:16
  • See the dupe reason - https://stackoverflow.com/questions/8575281/regex-plus-vs-star-difference: `+` = 1 or more, `*` = 0 or more. When the regex with `g` modifier can match an empty string, the lastIndex is not updated and you have an infinite loop. – Wiktor Stribiżew Feb 08 '18 at 09:18
  • @WiktorStribiżew i still don't get it `str.match(/(\d+)|([a-zA-Z]+)|(\^[a-zA-Z\d]+)/g)` works , but `str.match(/(\d*)|([a-zA-Z]*)|(\^[a-zA-Z\d]*)/g)` .... the only difference being .. i have changed the `+` to `*`. I have checked the dup question , but it does't really say anything about lastIndex being updated .... – Alexander Solonik Feb 08 '18 at 09:26
  • @WiktorStribiżew `So basically, if you use a + there must be at least one instance of the pattern, if you use * it will still match if there are no instances of it.` ... thats what your talking about i believe , i think i kind of get it ! – Alexander Solonik Feb 08 '18 at 09:28
  • 1
    See also [this answer of mine](https://stackoverflow.com/questions/34495675/zero-length-regexes-and-infinite-matches/34495840#34495840) to see how to manually move lastIndex. – Wiktor Stribiżew Feb 08 '18 at 09:31

0 Answers0