Home > Software design >  Find match within a first match
Find match within a first match

Time:09-21

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?

CodePudding user response:

Use lookarounds.

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

DEMO

CodePudding user response:

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

CodePudding user response:

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

  • Related