0

I need match the 4 pattern in equation like this type's

  1. _{num}
  2. _num
  3. ^{num}
  4. ^num

So i was created the regex pattern like this

/\_(\d+)|\^(\d{1})|\_\{(\d+)\}|\^\{(\d+)\}/g

Regex demo

This regex demo working perfect match but apply with javascript code its not working

var int_reg =/\_(\d+)|\^(\d{1})|\_\{(\d+)\}|\^\{(\d+)\}/g;
    var str = int_reg.exec('\int_5^{3}100x-100=10');
                        console.log(str)

Please Tell me what's the problem?.And correct my code with my goal

Thank's

prasanth
  • 22,145
  • 4
  • 29
  • 53
  • @WiktorStribiżew is nice .but i need match `^num` match only one number `(\d{1})` like this see my regex pattern.Without `{}` its match the one number.with `{}` match all numbers inside the `{}`.can you correct your code like this flow – prasanth Jan 13 '17 at 12:06
  • 1
    If you want to match `^1` in `2^1-5` and not `^1` in `2^12-5` add `\b`: `\^(\d)\b`. – Wiktor Stribiżew Jan 13 '17 at 12:13
  • Just got interested if it can really be contracted, but it is not that easy to make it an easy one-liner. You might use `s.match(/[_^](?:(?={\d}){|)\d+/g).map(x=>x.replace(/^\D+/, ""))`, but it will require additional post-process. Else, you will need to capture the number as shown in the duped question. – Wiktor Stribiżew Jan 13 '17 at 13:52
  • Thanks @WiktorStribiżew .Already i got the answer – prasanth Jan 13 '17 at 13:58

1 Answers1

1

It works fine, but the array you get is an array of captures (e.g. stuff matched in ()) of one match operation. To match further, you need to invoke exec again, like so:

var int_reg =/\_(\d+)|\^(\d{1})|\_\{(\d+)\}|\^\{(\d+)\}/g;
var str = '\int_5^{3}100x-100=10';
console.log(int_reg.exec(str))
console.log(int_reg.exec(str))
console.log(int_reg.exec(str))

Edit to address your additional question (even though the question has been closed):

var int_reg =/\_\d+|\^\d|\_\{\d+\}|\^\{\d+\}/g;
var str = '\int_5^{3}100x-100=10';
console.log(str.match(int_reg).map(s => Number((/\d+/.exec(s))[0])))
Lucero
  • 59,176
  • 9
  • 122
  • 152