Home > other >  Regular expression for matching 2 digits following anything not 'k' or ' k'
Regular expression for matching 2 digits following anything not 'k' or ' k'

Time:01-19

How do I create a regex where I need to match with 2 digits followed by any thing but 'k' or ' k'. For eg

['10', '10 a', '10 k', '10k']

In the given array only first and second element should be matched. That is '10' and '10 a'.

I tried giving [0-9]{2}(^k| k). Didn't give the expected result

CodePudding user response:

To match a number containing only two digits that is not followed with a single word k with a space or no space before it, you can use

\b\d{2}\b(?!\s*k\b)

See the regex demo. Details:

  • \b - word boundary
  • \d{2} - two digits
  • \b - a word boundary
  • (?!\s*k\b) - a negative lookahead that fails the match if there are zero or more whitespaces followed with k and a word boundary immediately to the right of the current location.

Note that your array items start with numbers, so it makes sense to replace the first word boundary with a ^ start of string anchor.

In JS, you can use

const arr = ['10', '10 a', '10 k', '10k'];
console.log(arr.filter(x => /^\d{2}\b(?!\s*k\b)/.test(x)));

Output:

[
  "10",
  "10 a"
]

CodePudding user response:

With js:

['10', '10 a', '10 k', '10k']
.filter(x => /\b\d{2}(?!\s*k)/
.test(x))
.forEach(x => console.log(x))

The regular expression matches as follows:

Node Explanation
\b the boundary between a word char (\w) and something that is not a word char
\d{2} digits (0-9) (2 times)
(?! negative look ahead to see if there is not:
\s* whitespace (\n, \r, \t, \f, and " ") (0 or more times (matching the most amount possible))
k k
) end of look-ahead

Output

10
10 a
  • Related