[英]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. 我试图在两个单词之间搜索一个单词,并在Java中使用Pattern类。 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. 第一个模式词“ PlaintiffAtty_0”将随着数字的增加而改变,因此我想将其用作变量。 How would insert a variable there instead of having to change the string every time?
如何在其中插入变量,而不必每次都更改字符串?
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
是变量,方法调用,对数组的访问等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.