我正在尝试从代码语句和“if”条件中提取变量。我有一个正则表达式,但 mymatcher.find()
没有返回任何匹配的值。
我不知道出了什么问题。
这是我的代码:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class test {
public static void main(String[] args) {
String test="x=y+z/n-10+my5th_integer+201";
Pattern mypattern = Pattern.compile("^[a-zA-Z_$][a-zA-Z_$0-9]*$");
Matcher mymatcher = mypattern.matcher(test);
while (mymatcher.find()) {
String find = mymatcher.group(1) ;
System.out.println("variable:" + find);
}
}
}
最佳答案
您需要删除分别断言字符串开始和结束位置的 ^
和 $
anchor ,并使用 mymatcher.group(0)
而不是 mymatcher.group(1)
因为您的正则表达式中没有任何捕获组:
String test="x=y+z/n-10+my5th_integer+201";
Pattern mypattern = Pattern.compile("[a-zA-Z_$][a-zA-Z_$0-9]*");
Matcher mymatcher = mypattern.matcher(test);
while (mymatcher.find()) {
String find = mymatcher.group(0) ;
System.out.println("variable:" + find);
}
参见 IDEONE demo ,结果为:
variable:x
variable:y
variable:z
variable:n
variable:my5th_integer
关于java - 使用正则表达式从代码语句中提取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33331716/