Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Created August 8, 2017 04:03
Show Gist options
  • Save vxhviet/6533c0be8ccc310edb4b10d90d0d383b to your computer and use it in GitHub Desktop.
Save vxhviet/6533c0be8ccc310edb4b10d90d0d383b to your computer and use it in GitHub Desktop.
Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Source: StackOverflow

Question: Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Answer:

Easy done:

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

Technically that's using lookaheads and look behinds. See Lookahead and Lookbehind Zero-Width Assertions. The pattern consists of:

  • is preceded by a [ that is not captured (lookbehind);

  • a non-greedy captured group. It's non-greedy to stop at the first ]; and

  • is followed by a ] that is not captured (lookahead).

Alternatively you can just capture what's between the square brackets:

\[(.*?)\]

and return the first captured group instead of the entire match.

Example: Use this to replace long log String in Notepad ++:

08-08 10:35:38.490 6338-6338/co.shutta.shuttapro D/EditImageActivity: setCropData(): DEBUG_SET_CROP
08-08 10:35:38.491 6338-6338/co.shutta.shuttapro D/MyTransformImageView: setImageUri(): DEBUG_SET_CROP
08-08 10:35:38.613 6338-6338/co.shutta.shuttapro D/MyTransformImageView: onBitmapLoaded(): DEBUG_SET_CROP mBitmapDecoded: true --- mBitmapLaidOut: false
08-08 10:35:38.613 6338-6338/co.shutta.shuttapro D/MyTransformImageView: setImageBitmap(): DEBUG_SET_CROP

(?<=08)(.*?)(?=D/) will replace the substring from 08 to D.

@OMartinez-NeT
Copy link

Thanks for this explanation, it was useful, I have been working with regex before but I didn't know about Lookahead and Lookbehind Zero-Width Assertions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment