Regex to capture patterns using JavaScript

63 Views Asked by At

I am new to automation ! I use wdio5 , cucumber and selenium framework with gherkin language . I need to write a step file using JavaScript for the gherkin feature that needs to add these patterns

Examples

52.27 .27 2.27

I hope I asked the question correctly!! Junior developer in the house

Help

1

There are 1 best solutions below

0
Telman On

If I understood correctly you need a regex pattern to match the numbers you shared.

Here is an example of such a pattern:

/^[-+]?((\.\d+)|(\d+(\.\d+)?))$/

Where [-+]? to match the leading +/- sign, (\.\d+) to match the numbers with a leadiinig ., and (\d+(\.\d+)?) to match full numbers.

Should match the numbers like: '-1', '+1', '50', '.27', '2.27'

Snippet:

const testNumbers = ['-1', '+1', '50', '.27', '2.27'];
const pattern = /^[-+]?((\.\d+)|(\d+(\.\d+)?))$/;

const isAllMatched = testNumbers.every(testNumber => testNumber === testNumber.match(pattern)?.[0]);

console.log('isAllMatched: ', isAllMatched);