简体   繁体   English

如何在Pattern类中使用变量而不是字符串?

[英]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.

相关问题 如何在 Android Studio 的类中使用字符串值而不是硬编码文本? - How do I use a string value instead of hardcoded text in a class in Android Studio? 仅在运行时在字符串变量中找到类的名称时,如何使用类? - how do I use a class when I only find out its name in a string variable at run time? 如何为最终变量使用setter而不是构造函数? - How do I use a setter instead of a constructor for a final variable? 如何在另一个类中使用静态类中的变量? - How do I use a variable from a static class in another class? 如何将 Pattern 和 Matcher 与 StringBuffer 或 char[] 类型而不是 String 一起使用? - How can I use Pattern and Matcher with StringBuffer or char[] types instead of String? 如何使用一种正则表达式模式使String成为Java中的另一种正则表达式模式? - How do I use one regex pattern to make a String become another regex pattern in Java? 如何使用另一个类中的对象的特定变量? - How do I use a specific variable of an object that is in another class? 如何在Java中使用或创建私有类的变量 - How do I use or create a variable of a private class in Java 如果类具有无法使用的Builder模式,如何正确设置变量 - How to set the variable correctly if the class has a Builder pattern which I cannot use 如何在数学方程式中使用字符串变量名称? - How do I use string variable names in Math equations?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM