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,我有以下字符串 aaaa#include(soap1.xml)bbbb #include(soap2.xml)cccc #include(soap2.xml) 我想查找所有出现的#include([anyfilename]),其中[anyfilename]各不相同 我有正则表达式(?您可以使用以下正则表达式: #include\(([^)]*)\) 见 我将lookarounds(即零宽度断言,不使用文本,不在匹配值中返回文本)替换为使用等价物 正则表达式细分: #include\(-匹配

我有以下字符串

aaaa#include(soap1.xml)bbbb #include(soap2.xml)cccc #include(soap2.xml)
我想查找所有出现的
#include([anyfilename])
,其中
[anyfilename]
各不相同


我有正则表达式
(?您可以使用以下正则表达式:

#include\(([^)]*)\)

我将lookarounds(即零宽度断言,不使用文本,不在匹配值中返回文本)替换为使用等价物

正则表达式细分:

  • #include\(
    -匹配文字符号序列
    #include(
  • ([^]*)
    -组1(我们将使用
    匹配器引用组内的值。组(1)
    )匹配零个或多个字符,而不是
  • \)
    -匹配文字
可以使用相同的模式检索文件名,并从输入中删除整个
#include()
s

:

String str=“aaaa#include(soap1.xml)bbbb#include(soap2.xml)cccc”;
字符串p=“#include\\([^)]*)\\”;
Pattern ptrn=Pattern.compile(p);
Matcher Matcher=ptrn.Matcher(str);
List arr=new ArrayList();
while(matcher.find()){
arr.add(matcher.group(1));//获取组1的值、文件名
}
System.out.println(arr);//=>[soap1.xml,soap2.xml]
System.out.println(str.replaceAll(p,“”);//=>AAABBCCC

预期结果是什么?请将您当前的代码添加到答案中。是否要删除
#include(soap2.xml)
#include(soap1.xml)
?“使用此方法执行替换时,会留下
#include()
”好的,环顾机制是(它们不包括在匹配中-您要替换的机制中),因此行为是预期的。你还期望什么?为什么?我共享了一个错误的链接:)我将发布一个答案。
\)*\)
\)+
相同,这在意图上更清晰。那么,为什么要匹配多个右括号呢?现在,积极的向后看/向前看将检查是否存在,而不包括在内。如果你想把他们包括在比赛中,只需去掉后面看/前面看的部分。因为你的捕获组将等于整个比赛,所以没有必要捕获。因此,这将导致:
\include\(.*)+
(请参阅)。
String str = "aaaa#include(soap1.xml)bbbb#include(soap2.xml)cccc";
String p = "#include\\(([^)]*)\\)";
Pattern ptrn = Pattern.compile(p);
Matcher matcher = ptrn.matcher(str);
List<String> arr = new ArrayList<String>();
while (matcher.find()) {
    arr.add(matcher.group(1));       // Get the Group 1 value, file name
}
System.out.println(arr); // => [soap1.xml, soap2.xml]
System.out.println(str.replaceAll(p, "")); // => aaaabbbbcccc