Viswanath Lekshmanan
Viswanath Lekshmanan

Reputation: 10083

Extract all values matching a specific pattern

I have an input string

var input = 'J1,J2, J3';

I'm using the following pattern to extract the group value

var regex = /(,? ?(?<JOUR>J[0-9]+)+)/

while extracting the groups as below

var match = regex.exec(input);

match.groups contains only one group. How can i get all the groups J1 J2 and J3 from the input string ?

Upvotes: 0

Views: 142

Answers (4)

Pablo
Pablo

Reputation: 2305

const input = 'J1,J2, J3,J10';
const regexJfollowOneDigit = /(J\d{1}(?!\d))/g
const regexJfollowOneOrMoreDigit = /(J\d+)/g
console.log(input.match(regexJfollowOneDigit))
console.log(input.match(regexJfollowOneOrMoreDigit))

Upvotes: 0

The fourth bird
The fourth bird

Reputation: 163467

You could take the start of the string and the comma with an optional space into account and remove the outer group to use only 1 capturing group. To prevent the digits being part of a larger word you might add a word boundary \b

Note that you can omit the quantifier+ after )+ because that will repeat the group and will give you only the value of the last iteration.

(?:^|[,-] ?)(?<JOUR>J[0-9]+)\b
  • (?:^|[,-] ?) Match either the start of the string or comma or hyphen with an optional space
  • (?<JOUR>J[0-9]+) Named capture group JOUR, match J and then 1+ digits
  • \b Word boundary to prevent the digits being part of a larger word

Regex demo

Use exec to get the value from the first capturing group

const regex = /(?:^|, ?)(?<JOUR>J[0-9]+\b)+/g;
let m;

[
  "J1, J2, J3 - J5, J7",
  "J1,J2, J3"
].forEach(str => {
  while ((m = regex.exec(str)) !== null) {
    if (m.index === regex.lastIndex) {
      regex.lastIndex++;
    }
    console.log(m[1]);
  }
});

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44125

Match a capital J, then any amount of numbers:

var input = 'J1,J2, J3';
var regex = /J[0-9]+/g;
console.log(input.match(regex));

Upvotes: 0

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

You can use .match of string to get groups

input.match(/J[0-9]+/g)

var input = 'J1,J2, J3';
console.log(input.match(/J[0-9]+/gi))

Upvotes: 1

Related Questions