bopapa_1979
bopapa_1979

Reputation: 9237

Regex to get text BETWEEN two characters

PLEASE READ CAREFULLY: This is a bit unusual and you will be tempted to say things like "that isn't how to use a regex" or "dude, just use String.SubString()," Etc...

I have a need to write a regex (to use a pre-existing method) that will match text BETWEEN curly braces, BUT NOT the curly braces themselves.

For Example: "{MatchThisText}" AND "La la la {MatchThisText} la la la..."
Should Both Match: "MatchThisText"

Someone asked this exact question a year ago, and he got a bunch of solutions for regexes that WILL match the curly braces in addition to "MatchThisText," resulting in a match of "{MatchThisText}" which is not what he (or I) needed.

If someone can write a Regex that actually matches only the characters BETWEEN the curly braces, I'd really appreciate it. It should allow any ASCII values, and should stop the match at the FIRST closing bracket.

For Example: "{retailCategoryUrl}/{filters}"
Should Match: retailCategoryUrl and filters
But NOT Match: "retailCategoryUrl}/{filters" (Everything but the outer braces)

Hey, this is a really tricky one for me, so please forgive the question if this is trivial for some of you.

THANKS!

Upvotes: 20

Views: 44959

Answers (5)

pungggi
pungggi

Reputation: 1263

In Javascript you get an array with all matches. Here is an example that machtes text between css` and ` for machting template strings:

yourstring.match(/css`([^}]+).`/gmi)

Upvotes: 0

Tiberiu Craciun
Tiberiu Craciun

Reputation: 3271

current answer works with .NET Regex but need to remove the curly braces from all matches:

var regex = new Regex(@"(?<={)[^}]*(?=})", RegexOptions.Compiled);
var results = regex.Matches(source)
                   .Cast<Match>()
                   .Select(m => m.Value.TrimStart('{').TrimEnd('}'));

Upvotes: 0

Daniel Mendel
Daniel Mendel

Reputation: 10003

If you're using a RegExp engine with lookahead and lookbehind support like Python, then you can use

/(?<={)[^}]*(?=})/

If it doesn't (like javascript), you can use /{([^}]*)}/ and get the substring match. Javascript example:

"{foo}".match(/{([^}]*)}/)[1] // => 'foo'

Upvotes: 12

steinar
steinar

Reputation: 9663

You'll need a non-greedy match operator, *?, to stop the match as soon as the engine sees a closing curling brace. Then you need to group what's inside the braces, using parentheses. This should do it:

{(.*?)}

You will then need to get the value from group number 1 in your regex API. (How you do that depends on your programming language/API.)

Upvotes: 8

Douglas Leeder
Douglas Leeder

Reputation: 53320

Python:

(?<={)[^}]*(?=})

In context:

#!/usr/bin/env python

import re

def f(regexStr,target):
    mo = re.search(regexStr,target)
    if not mo:
        print "NO MATCH"
    else:
        print "MATCH:",mo.group()

f(r"(?<={)[^}]*(?=})","{MatchThisText}")
f(r"(?<={)[^}]*(?=})","La la la {MatchThisText} la la la...")

prints:

MATCH: MatchThisText
MATCH: MatchThisText

Upvotes: 17

Related Questions