- I would like to capture the set of characters from a string that matches the pattern using nodejs
ex: const inputString = ' abc 1 2 3 white_rabbit_123_456_789.txt pqr ';
const pattern = 'white_rabbit_*_*_*.txt'
expected output is white_rabbit_123_456_789.txt
I am okay if the output is a string or an array.
- Also, now lets say I have multiple instances of pattern in the inputString
ex: const inputString = ' abc 1 2 3 white_rabbit_123_456_789.txt pqr
white_rabbit_312_456_888.txt';
const pattern = 'white_rabbit_*_*_*.txt'
expected output is ['white_rabbit_123_456_789.txt','white_rabbit_312_456_888.txt']
Any suggestion would be very helpful. Thanks!
CodePudding user response:
try this
const inputString1 = ' abc 1 2 3 white_rabbit_123_456_789.txt pqr ';
const inputString2 = ' abc 1 2 3 white_rabbit_123_456_789.txt pqr white_rabbit_312_456_888.txt';
const _match = string => string.match(/white_rabbit_\d _\d _\d .txt/g);
console.log(_match(inputString1));
console.log(_match(inputString2));
CodePudding user response:
You could use String.prototype.match() passing a RegExp argument:
const inputString = ` abc 1 2 3 white_rabbit_123_456_789.txt pqr
white_rabbit_312_456_888.txt
white_rabbit_199212223_8888888_13456787.txt
white_rabbit_1_2_3.txt
white_rabbit_444_555_666_777.txt
white_rabbit_888_999.txt`
const matchArray = inputString.match(/white_rabbit(?:_\d ){3}.txt/g)
console.log(matchArray)
I created a literal RegExp object (pattern between two forward slashes, followed by a global flag), in whose pattern I used a non-capturing group for "an underscore and one-or-more digits" repeated exactly 3 times.