Christopher Townsend
Christopher Townsend

Reputation: 1746

Find match within a first match

I have the following string

abc123+InterestingValue+def456

I want to get the InterestingValue only, I am using this regex

\+.*\+

but the output it still includes the + characters

Is there a way to search for a string between the + characters, then search again for anything that is not a + character?

Upvotes: 1

Views: 62

Answers (3)

The fourth bird
The fourth bird

Reputation: 163342

If it should be the first match, you can use a capture group with an anchor:

^[^+]*\+([^+]+)\+
  • ^ Start of string
  • [^+]* Optionally match any char except + using a negated character class
  • \+ Match literally
  • ([^+]+) Capture group 1, match 1+ chars other than +
  • \+ Match literally

Regex demo

Upvotes: 2

Jesse
Jesse

Reputation: 1425

You can use a positive lookahead and a positive lookbehind (more info about these here). Basically, a positive lookbehind tells the engine "this match has to come before the next match", and a positive lookahead tells the engine "this has to come after the previous match". Neither of them actually match the pattern they're looking for though.

A positive lookbehind is a group beginning with ?<= and a positive lookahead is a group beginning with ?=. Adding these to your existing expression would look like this:

(?<=\+).*(?=\+)

regex101

Upvotes: 2

Barmar
Barmar

Reputation: 780984

Use lookarounds.

(?<=\+)[^+]*(?=\+)

DEMO

Upvotes: 2

Related Questions