javaregex

Use variables in pattern


So i need to get a word between 2 other words; and im using pattern and matcher.

Pattern p = Pattern.compile("Hello(.*?)GoodBye");
Matcher m = p.matcher(line);

In this example i'm getting the word between Hello and Goodbye and it works. What i want to do is replace Hello and GoodBye bye variables such as:

String StartDelemiter = "Hello";
String EndDelemiter = "GoodBye";

How should write it in Pattern p = Pattern.compile(---); I Tried :

Pattern p = Pattern.compile( "{ "+StartDelemiter +" (.*?) "+EndDelemiter+" }"  );

But application crashes !!


Solution

  • You need to escape { and } with backslashes, something like:

    Pattern p = Pattern.compile( "\\{ "+StartDelemiter +" (.*?) "+EndDelemiter+" \\}"  );
    

    The curly braces are Regex quantifiers

    <pattern>{n}    Match exactly n times 
    <pattern>{n,}   Match at least n times 
    <pattern>{n,m}  Match at least n but not more than m times