Daniel
Daniel

Reputation: 1564

How to express the intention of matching a string only when it's followed by pattern in regular expression

Say I wanted to match a target string "abc" only when it's followed by "def", yet I only want the matched part to be "abc" instead of "abcdef".

in a more general sense, I wanted to match a string against pattern1 only when it's followed by pattern2, yet the matched part is only pattern1 instead of pattern1 followed by pattern2.

How can I do that?

Upvotes: 0

Views: 39

Answers (3)

Jason Larke
Jason Larke

Reputation: 5609

There are a few ways to go about this.

Option a) Grouping

(pattern1)(?:pattern2)

You group pattern1 within a capturing group, with pattern2 in a non-capturing group (represented by the ?: at the start of the group). Without a language specified in your question I can't give you much more detail about accessing the contents of captured groups, but it's a standard feature in all RegEx implementations in every language I've come across.

Option b) Lookaheads

This is a particularly useful option when you don't want to consume pattern2 within the string when performing the match:

pattern1(?=pattern2)

Lookarounds are summarised exhaustively here. But essentially they boil down to exactly what you want: pattern1 followed by pattern2 without consuming or including pattern2 in the match.

Upvotes: 1

Peter Alfvin
Peter Alfvin

Reputation: 29419

You want the "lookahead" function, as follows:

abc(?=def)

See http://www.regular-expressions.info/lookaround.html for more information.

The other answers deal with "capture groups" which will isolate the "abc" for you, but end up matching the text that follows as well, in terms of the overall match.

Upvotes: 2

Connor
Connor

Reputation: 64654

You can use match groups to capture a part of your regex.

(abc)def

abc is captured only if it is followed by def.

Upvotes: 0

Related Questions