我想在文件中替换字符串,当我看到hostName=some_word时,我想用some_other_word替换它,但是我使用的零宽度负查找regex在java代码中似乎失败了,尽管我在一个在线java regex测试器上测试它时,它还在工作。
line = "hostName=testing"
Pattern host = Pattern.compile("(?<=hostName=).*");
Matcher match = host.matcher(line);
hostName = match.group(); //illegal state exception
line.replace(hostName,"new_name");我在网上的字符串上尝试了这个正则表达式,它似乎运行得很好:
链接:http://ocpsoft.org/tutorials/regular-expressions/java-visual-regex-tester/#!;t=hostName%3Dtesting&r=(%3F%3C%3DhostName%3D).*&x=new_name
发布于 2014-10-01 16:28:04
在调用matcher.find()之前,需要调用matcher.group() (在输入中匹配)或调用matcher.matches() (整个输入匹配)。
通常在if条件内(如果迭代匹配,则在while循环中)。
参见API接口以获取Matcher.group()
抛出: IllegalStateException -如果还没有尝试匹配,或者如果上一次匹配操作失败
https://stackoverflow.com/questions/26146018
复制相似问题