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:
我试图在两个单词之间搜索一个单词,并在Java中使用Pattern类。到目前为止我的代码是:
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?
第一个模式词“PlaintiffAtty_0”将随着数字的增加而改变,所以我想将它用作变量。如何在那里插入变量而不必每次都更改字符串?
1 个解决方案
#1
3
Use string concatenation and Pattern.quote
to ensure that any special characters inside the string are treated literally:
使用字符串连接和Pattern.quote确保字符串中的任何特殊字符都按字面处理:
Pattern.compile("(?<="+Pattern.quote(myString)+").*?(?=</span>)");
where myString
is a variable, a method call, an access to an array, etc.
其中myString是变量,方法调用,对数组的访问等。
#1
3
Use string concatenation and Pattern.quote
to ensure that any special characters inside the string are treated literally:
使用字符串连接和Pattern.quote确保字符串中的任何特殊字符都按字面处理:
Pattern.compile("(?<="+Pattern.quote(myString)+").*?(?=</span>)");
where myString
is a variable, a method call, an access to an array, etc.
其中myString是变量,方法调用,对数组的访问等。