gpt4 book ai didi

java - RegEX 修剪前两个字符

转载 作者:行者123 更新时间:2023-11-30 04:17:53 26 4
gpt4 key购买 nike

我正在尝试使用 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)

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

See online demo here .

关于java - RegEX 修剪前两个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17892792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com