ryandlf
ryandlf

Reputation: 28545

Java Regex Find All Between But Last Character Not Preceded Or Followed By

I have a string: "stuffhere{@ name="productViewer" vars="productId={{id}}"}morestuff"

How can I find everything between the beginning { and last }.

Pattern.compile("\\{@(.*?)\\}" + from, Pattern.DOTALL); //Finds {@ name="productViewer" vars="productId={{id}

How can I verify that the ending } is not preceded or followed by another }? The string may also be surrounded by other characters.

Id like for the regex to only return: name="productViewer" vars="productId={{id}}"

Upvotes: 1

Views: 126

Answers (4)

android_su
android_su

Reputation: 1687

try this:

    String s = "stuffhere{@ name=\"productViewer\" vars=\"productId={{id}}\"}morestuff";
    Pattern p = Pattern.compile("\\{@\\s+(.*)\\}");
    Matcher m = p.matcher(s);
    if(m.find()){
        System.out.println(m.group(1));
    }

Upvotes: 0

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

You can use this pattern:

\\{@(.*)(?<!\\})\\}

(?<!..) is a negative lookbehind that checks your condition (not preceded by })

Note that closing curly brackets don't need to be escaped, you can write:

\\{@(.*)(?<!})}

Upvotes: 4

gwillie
gwillie

Reputation: 1899

how about

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

i have never used java, but regex is international isn't it :)

EDIT:

wait... regex has errors...

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 32831

Try this:

 ^[^{]*\\{@(.*?)\\}[^}]*$

Upvotes: 0

Related Questions