Reputation: 365
How can I use regex to get 1 or 2 characters after a specific character -
?
For example:
33225566-69 => 69
33225544-5 => 5
But I don't want more than 3 characters:
33226655-678 => Do not select
Lookbehind is not supported in some browsers. I want the regex command without lookbehind.
Upvotes: 0
Views: 3043
Reputation: 370769
Just match the -
, then capture 2 digits, negative lookahead for another digit, and extract the captured group, if it exists. In Javascript, for example:
['33225566-69', '33225544-5', '33226655-678'].forEach((str) => {
const match = str.match(/-(\d{1,2})(?!\d)/);
console.log(
match
? match[1]
: 'No Match'
);
});
If the part with the -
and the numbers are always at the end of the string, then use $
instead of the lookahead:
-(\d{1,2})$
Upvotes: 3