我正在尝试使用 Java 中的匹配器从正则表达式的行中提取两个单词 我的线路是这样的,BROWSER=Firefox
我使用下面的代码
currentLine = currentLine.trim();
System.out.println("Current Line: "+ currentLine);
Pattern p = Pattern.compile("(.*?)=(.*)");
Matcher m = p1.matcher(currentLine);
if(m.find(1) && m.find(2)){
System.out.println("Key: "+m.group(1)+" Value: "+m.group(2));
}
我得到的输出是 键:OWSER 值:FireFox
就我而言,BR 正在被削减。这对我来说似乎很奇怪,直到我知道它为什么会这样,因为这与 PERL 完美配合。有人可以帮助我吗?
最佳答案
当您调用m.find(2)
时它会删除前两个字符。 From the JavaDocs (粗体是我的):
public boolean find(int start)
block 引用>Resets this matcher and then attempts to find the next subsequence of the input sequence that matches the pattern, starting at the specified index.
所以,只使用
m.find()
:String currentLine = "BROWSER=FireFox"; System.out.println("Current Line: "+ currentLine); Pattern p = Pattern.compile("(.*?)=(.*)"); Matcher m = p.matcher(currentLine); if (m.find()) { System.out.println("Key: "+m.group(1)+" Value: "+m.group(2)); }
输出:
Current Line: BROWSER=FireFox Key: BROWSER Value: FireFox
关于java - RegEX 修剪前两个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17892792/