0

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.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Elham AM
  • 375
  • 5
  • 15
  • Are you asking about JavaScript? – melpomene Jun 02 '19 at 09:08
  • For your samples like this would be sufficient: [`\b-(\d\d?)\b`](https://regex101.com/r/dezvoC/1). A word boundary followed by a hyphen, capture 1 or 2 digits, followed by another word boundary. – bobble bubble Jun 02 '19 at 09:19

1 Answers1

3

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})$
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • `[0-9]` could also be written as `\d`. – melpomene Jun 02 '19 at 09:08
  • You can, but `\d` is slower and can match other odd digit-like characters as well (which are *not* `[0-9]`), so unless those are specified as required, I prefer using `[0-9]` – CertainPerformance Jun 02 '19 at 09:09
  • `\d` is exactly equivalent to `[0-9]`. – melpomene Jun 02 '19 at 09:10
  • Oh, it looks like you're right, thanks. I saw [this](https://stackoverflow.com/questions/16621738/d-is-less-efficient-than-0-9) a while ago and remembered that a similar problem resulted from `\d` in Python so I had been thinking what `\d` meant was universal, but it's not! – CertainPerformance Jun 02 '19 at 09:14
  • 1
    Yeah, this depends a lot on the regex implementation. In JS and vim `\d` simply means `[0-9]`, in other languages it matches any Unicode digit, and in Perl it can do either (the `/a` flag restricts it to ASCII digits). – melpomene Jun 02 '19 at 09:17
  • Thanks. But I do not want to (-) choose. only number selected. – Elham AM Jun 02 '19 at 09:27
  • @ElhamAM What do you mean by `But I do not want to (-) choose`? I don't understand. Javascript doesn't have anything like `\K` unfortunately, so you *have* to match the `-` (since you said you didn't want to use lookbehind) – CertainPerformance Jun 02 '19 at 09:28
  • The output of your regex is "-69" , but I want "69" – Elham AM Jun 02 '19 at 09:32
  • 1
    @ElhamAM Press "Run code snippet", and you'll see that it works as desired - you just need to extract the captured group when there's a match, and you'll get the digits. – CertainPerformance Jun 02 '19 at 09:33