Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 前两个字符中的正则表达式_Java_Regex - Fatal编程技术网

Java 前两个字符中的正则表达式

Java 前两个字符中的正则表达式,java,regex,Java,Regex,我试图使用Java中的matcher从带有正则表达式的行中提取两个单词 我的台词是这样的,BROWSER=Firefox 我正在使用下面的代码 currentLine = currentLine.trim(); System.out.println("Current Line: "+ currentLine); Pattern p = Pattern.compile("(.*?)=(.*)"); Matcher m = p1.matcher(currentLine); if(m.find(1)

我试图使用Java中的matcher从带有正则表达式的行中提取两个单词 我的台词是这样的,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中非常有效。有人能帮我吗?

您可以使用查找
=
的位置,然后获取两个值:

String currentLine = "BROWSER=Firefox";

int indexOfEq = currentLine.indexOf('=');

String myKey = currentLine.substring(0, indexOfEq);
String myVal = currentLine.substring(indexOfEq + 1);

System.out.println(myKey + ":" + myVal);
当您调用
m.find(2)
时,它会删除前两个字符。(粗体字是我的):

公共布尔查找(int start)

重置此匹配器,然后尝试查找与模式匹配的输入序列的下一个子序列,从指定索引开始。

因此,只需使用
m.find()

输出:

Current Line: BROWSER=FireFox
Key: BROWSER Value: FireFox

.

当前线路的值是多少?在
System.out.println(“当前行:+currentLine”)中打印的一个
@AdrianWragg(.*)是不相关的,它只意味着一个非贪婪匹配,这将使正则表达式引擎在第一个=符号处停止,而不是狼吞虎咽然后回溯。在这种情况下,这不是绝对必要的,但可以稍微提高效率。很好,这是正确的诊断和解决方案。但是,指向此表单的链接是以下链接(不过,这只是页面上的下一个链接):
Current Line: BROWSER=FireFox
Key: BROWSER Value: FireFox