Exclude a certain match in a capturing group in regex

15,325

You'll want to use a negative lookahead to "stop" the match if something after matches your pattern. So, something like this might work:

(\\n(?![0-9][a-zA-Z]))

See it in use here: https://regex101.com/r/zL1tL8/2

Here's a page with some more info on lookahead and lookbehind: http://www.rexegg.com/regex-lookarounds.html

Share:
15,325
oyan11
Author by

oyan11

newbie

Updated on June 13, 2022

Comments

  • oyan11
    oyan11 almost 2 years

    I have a regex capturing group and I want to exclude a number if it matches a certain pattern also.

    This is my capturing group:

    https://regex101.com/r/zL1tL8/1

    if \n is followed by a number and character like "1st", "2nd", "4dffgsd", "3sf" then it should stop the match BEFORE the number.

    0-9 is important in the capturing group.

    So far I have this pattern [0-9][a-zA-Z]+ to match a number followed by characters. How do I apply this to the capturing group as a condition?

    Update:

    https://regex101.com/r/zL1tL8/4

    Line 1 is wrong.

    It should not match a number followed by characters

    • Admin
      Admin over 8 years
      Can you post the text of the regex instead of a link to it.
    • Admin
      Admin over 8 years
      It's unclear if \n is a newline (0x0a) or a literal \ plus n. It's also nclear what you are trying to match.
    • oyan11
      oyan11 over 8 years
      Hi, i edited the sample regex already. what i really want is to un match if there's a number followed by characters \n1st should not match 1st. but it should match \n$300 or \n599
    • Jake Bathman
      Jake Bathman over 8 years
      Did you look at my answer below? It should do what you're looking for.
  • Jon
    Jon over 7 years
    It is assumed that the OP knows then how to then capture everything after "\n", but for completeness's sake, ^\\n(?![0-9][A-Z])(.+)$ contains a capturing group that captures everything after the "\n" (as "i" was used in linked example, I omitted the "a-z" from the character class). "^" and "$" anchors are necessary given "m" modifier.