-3

I want to extract ABC and XZ from the following string:

  • ABC XYZ

I tried this:

  • (ABC) (X(?:Y)Z)

But it extracts ABC and XYZ.

GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
  • No that does not answer my question and I do not appreciate closing my question like that. – GirkovArpa Jul 27 '20 at 17:20
  • You do have a capturing group *around* the non-capturing group, so of course it shows up in the result…‽ – deceze Jul 27 '20 at 17:21
  • I need to extract `ABC` and `XZ` from `ABC XYZ`. So yes I need to exclude the `Y` from the second group, hence the nested non-capturing group. – GirkovArpa Jul 27 '20 at 17:25
  • `(ABC) (X(?:Y)Z)` – GirkovArpa Jul 27 '20 at 17:26
  • Why doesn't it work? I won't know because my question is closed and pointed to a useless answer. – GirkovArpa Jul 27 '20 at 17:26
  • A non-capturing group won’t exclude anything from a surrounding capturing group. That’s not what it does. It’s just a group which you can use for its grouping behavior, *without having it show up as an additional capture.* – deceze Jul 27 '20 at 17:27
  • Then how do I extract `XZ` from `XYZ`? – GirkovArpa Jul 27 '20 at 17:28
  • Rephrase your question towards that and away from the red herring of non-capturing groups, and this could be reopened. – deceze Jul 27 '20 at 17:30
  • 1
    You can't have non consecutive characters in a single group. It's the normal behaviour of regex. It's not possible to extract `XZ` from `XYZ`, there're absolutly no way to do such job. – Toto Jul 27 '20 at 18:18
  • The [Why isn't the regular expression's “non-capturing” group working?](https://stackoverflow.com/a/2703139/3832970) explains that *"the text matched by a non-capturing group still becomes part of the overall regex match"* and **is a valid answer to this question, too**. @deceze Please consider reclosing. – Wiktor Stribiżew Jul 27 '20 at 18:46

2 Answers2

0

I have been informed that this is, in fact, impossible.

GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
0

I'm not sure if this will be helpful to you at all, but I noticed you added a javascript tag.

If you want, you could try the following regex: https://regex101.com/r/JB3iNj/1

With the following code:

    var myString = "ABC XYZ";
    var myRegexp = /(ABC) (X)Y(Z)/g;
    match = myRegexp.exec(myString);
    var s1 = match[1]
    var s2 = (match[2] + match[3])
    console.log(s1 + " " + s2)
aaaa
  • 246
  • 1
  • 9
  • 2
    I know it's not a great answer, but didn't want you to feel like all was lost. If you tell us more about your use case, might be able to help to a better degree. – aaaa Jul 27 '20 at 19:13