0

I am using Regular expression in the validation while I am trying to match the string with giving pattern, the result is not as expected

Pattern: (?:[0-9])*21([a-zA-Z0-9-]{1,15})

Expected result: I do not want to capture the letters or number until it matches 21, which means

Example: I have a string, In this string, I do not want to capture the number and letter which is before 21 i.e I don't want to capture Aabcde12345 and the expected result should be 345621822 But, the result what I am getting is just 822 because in the number 345621822 21 will reoccur and gives me the result 822 which is wrong

can someone please help me

Note: Also Please help me to update start over Question according to it `

const text = "Aabcde1234521345621822";
const regex = "(?:[0-9])*21([a-zA-Z0-9-]{1,15})";
const result = text.match(regex);

console.log(result);

// expected output: Array [""1234521345621822"", "345621822"]

`

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Does it solve your problem? https://stackoverflow.com/questions/6323417/regex-to-extract-all-matches-from-string-using-regexp-exec – Carlos Saiz Orteu Apr 07 '20 at 15:50
  • Any other solution would be accepted or you want to solve it only with Regex? – Zain Ul Abideen Apr 07 '20 at 16:29
  • @CarlosSaizOrteu can you please help me with below question, this is what I wanted to solution https://stackoverflow.com/questions/61102152/how-to-capture-reoccurring-digit-by-using-regex-in-below-example – Vikas Kalapur Apr 08 '20 at 14:31
  • @Zain Ul Abideen can you please help me with below question, this is what I wanted to solution https://stackoverflow.com/questions/61102152/how-to-capture-reoccurring-digit-by-using-regex-in-below-example – Vikas Kalapur Apr 08 '20 at 14:31

1 Answers1

1

Just remove the capture group from the first part (the brackets) and add the ? to make the first digits as non-greedy

[0-9]*?21([a-zA-Z0-9-]{1,15})

KiaiFighter
  • 647
  • 5
  • 18
  • @Vikas If this answer solved your problem, please mark it accordingly :) Thank you! – KiaiFighter Apr 07 '20 at 16:47
  • this is working for this example, Marked it. can you please help me with below question, this is what I wanted to solution https://stackoverflow.com/questions/61102152/how-to-capture-reoccurring-digit-by-using-regex-in-below-example – Vikas Kalapur Apr 08 '20 at 14:23