I'm trying to take only expressions like 'A==1' or 'D1 >= 2' from a string (including spaces).
For example:
From - '(A == 3 AND B == 4) OR ( A==1 AND B==2)'
I expect to get: [A == 3, B == 4, A==1, B==2].
Here's my code:
let myString = '(A == 3 AND B == 4) OR ( A==1 AND B==2)';
const result = myString.match(/[a-z0-9\s] (>|<|==|>=|<=|!=|\s)\d/gi);
console.log(result); //result => [A == 3 ,AND B == 4,A==1 ,AND B==2]
I want my regex to take only the specific pattern of {param}{operator}{param} but with blank spaces.
I tried many ways, but none was successful.
I would appreciate any help.
CodePudding user response:
You might write the pattern with the case insensitive flag as:
\b[a-z0-9] \s*(?:[=!]=|[<>]=?)\s*\d \b
Explanation
\b
A word boundary to prevent a partial word match[a-z0-9]
Match 1 chars a-z or a digit 0-9\s*
Match optional whitspace cahrs(?:[=!]=|[<>]=?)
Match either=!
==
<
>
<=
>=
\s*
Match optional whitespace chars\d \b
1 digits and a word boundary
For only leading uppercase chars:
\b[A-Z] \s*(?:[=!]=|[<>]=?)\s*\d \b
const regex = /\b[A-Z] \s*(?:[=!]=|[<>]=?)\s*\d \b/g;
const s = `(A == 3 AND B == 4) OR ( A==1 AND B==2)`;
console.log(s.match(regex))
CodePudding user response:
Something like this would work:
[a-z\d] \s*[=<>!] \s*[a-z\d]
Explanation:
[a-z\d] \s*
- left side of comparison[=<>!]
- comparison operators\s*[a-z\d]
- right side of comparison
let myString = '(A == 3 AND B == 4) OR ( A==1 AND B==2)';
const result = myString.match(/[a-z\d] \s*[=<>!] \s*[a-z\d]/gi);
console.log(result);