cmart
cmart

Reputation: 91

How do I use a variable instead of a string in the Pattern class?

I am attempting to search for a word in between two words and am using the Pattern class in Java. So far my code is:

Pattern pattern = Pattern.compile("(?<=PlaintiffAtty_0).*?(?=</span>)");
Matcher matcher = pattern.matcher(sourcecode.toString());

        while (matcher.find()) {
            System.out.println(matcher.group().toString()); 

The first pattern word "PlaintiffAtty_0" will be changing as the number will increase, so I would like to use it as a variable. How would insert a variable there instead of having to change the string every time?

Upvotes: 0

Views: 74

Answers (1)

nanofarad
nanofarad

Reputation: 41271

Use string concatenation and Pattern.quote to ensure that any special characters inside the string are treated literally:

Pattern.compile("(?<="+Pattern.quote(myString)+").*?(?=</span>)");

where myString is a variable, a method call, an access to an array, etc.

Upvotes: 3

Related Questions