Ameya Salagre
Ameya Salagre

Reputation: 793

unable to extract string between patterns using Regex

My Input String :"CR 1513II2255651 202OL19010200785 FX:1 NEAT LIMITE mndfgusadg202OL19010200785 NEAT LIMITED NEAT LIMITED HKD 52194.2"

I want to extract anything in between FX:1 & the first alphanumeric word, in this case expected output is : NEAT LIMITE

I have tried below code but not getting desired solution

var str = "CR 1513II2255651 202OL19010200785 FX:1 NEAT LIMITE mndfgusadg202OL19010200785 NEAT LIMITED NEAT LIMITED HKD 52194.2"

var pattern = "FX:1 (.*) ((?=.*[0-9])(?=.*[a-zA-Z]))+"
str.match(pattern);

Upvotes: 2

Views: 50

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626919

You may use

var str = "CR 1513II2255651 202OL19010200785 FX:1 NEAT LIMITE mndfgusadg202OL19010200785 NEAT LIMITED NEAT LIMITED HKD 52194.2"

var pattern = /FX:1\s+(.*?)\s+(?:[a-zA-Z]+[0-9]|[0-9]+[a-zA-Z])/;
var result = str.match(pattern);
if (result) {
  console.log(result[1]); // Get only Group 1 value
}

Pattern details

  • FX:1 - a literal string
  • \s+ - 1+ whitespaces
  • (.*?) - Group 1: any 0+ chars as few as possible
  • \s+ - 1+ whitespaces
  • (?:[a-zA-Z]+[0-9]|[0-9]+[a-zA-Z]) - either
    • [a-zA-Z]+[0-9] - 1+ letters and then a digit
    • | - or
    • [0-9]+[a-zA-Z] - 1+ digits and then a letter.

See the Regulex graph:

enter image description here

Upvotes: 2

Related Questions