Search code examples
regexpartial-matches

Exclude last characters from regex pattern


How do i extract this from a regex:

mymatch[ someother char ]

What i want is mymatch when followed by a [ but i don't want the square bracket in the match.

I'm stuck on this but it gets also the square bracket:

\b.*?\[

More in general, how can i exclude from the match some portion of the pattern?

For example here (abc2)mymatch i want a regex returning my match only when it is preeceds by (abc2).


Solution

  • in this you need to use lookahead and lookbehind , in first one use positive lookahead :

    \w+(?=\[)
    

    ?=[ : mean followed by "[" and not catch in matches

    in second example use positive lookbehind :

    (?<=\(abc2\))\w+
    

    (?<=(abc2)) : mean leaded by "(abc2)" and not catch in matches

    for more information about lookahead and lookbehind