Regex match the unknown characters with dash between

Viewed 271

I'm struggling with the following combination of characters that I'm trying to parse:

I have two types of text:

1. AF-B-W23F4-USLAMC-X99-JLK
2. LS-V-A23DF-SDLL--X22-LSM

I want to get the last two combination of characters devided by - within dash.

From the 1. X99-JLK and from the 2. X22-LSM

I accomplished the 2. with the following regex '--(.*-.*)'

How can I parse the 1. sample and is there any option to parse it at one time with something like OR operator?

Thanks for any help!

2 Answers

The pattern --(.*-.*) that you tried matches the second example because it contains -- and it matches the first occurrence.

Then it matches until the end of the string and backtracks to find another hyphen.

As .* can match any character (also -) and there are no anchors or boundaries set, this is a very broad match.


If there have to be 2 dashes, you can match the first one, and use a capture group for the part with the second one using a negated character class [^-]

The character class can also match a newline. If you don't want to match a newline you can use [^-\r\n] or also not matching spaces [^-\s] (as there are none in the example data)

-([^-]+-[^-]+)$

Explanation

  • - Match -
  • ( Capture group 1
    • [^-]+-[^-]+ Match the second dash between chars other than -
  • ) Close group 1
  • $ End of string

See a regex demo

For example using Javascript:

const regex = /-([^-]+-[^-]+)$/;
[
  "AF-B-W23F4-USLAMC-X99-JLK",
  "LS-V-A23DF-SDLL--X22-LSM"
].forEach(s => {
  const m = s.match(regex);
  if (m) {
    console.log(m[1]);
  }
})

You can try lookahead to match the last pair before the new line. JavaScript example:

const str = `
  AF-B-W23F4-USLAMC-X99-JLK
  LS-V-A23DF-SDLL--X22-LSM
`;

const re = /[^-]*-[^-]*(?=\n)/g;

console.log(str.match(re));

Related