考虑下面的场景,我有一个输入字符串
"input [yes] [yes] [yes] [mk:[yes] [yes] [yes]] [yes] [iif:[yes] [yes] [yes]]"
我所需的out字符串在替换后全部[yes]
将被替换为Yes
但是如果它嵌套在辅助或n-bootets中这样的模式应该被忽略,这里的假设是所有开放括号将正确关闭,这是所需的输出字符串
"input Yes Yes Yes [mk:[yes] [yes] [yes]] Yes [iif:[yes] [yes] [yes]]"
这里是我的问题,简而言之,正则表达式可以理解'嵌套'模式?或者递归是实现这一目标的绝对必要条件,正则表达式还不够
如果检测到无限嵌套的正则表达式无法完成,那么嵌套到第二度的方式就像我的例子一样
答案 0 :(得分:2)
编辑1
由于vks指出这不能用正则表达式完成,我写了一个简单的程序,它将在Java中为你做同样的事情:
public class Main {
public static String nestedReplace(String s) {
int nested =0,i=0;
StringBuilder o = new StringBuilder();
while(i<s.length())
{
if(nested==0 && s.regionMatches(i,"[yes]",0,4))
{
o.append("Yes");
i += 5;
continue;
}
else if(s.charAt(i) == '[')
nested++;
else if(s.charAt(i) == ']')
nested--;
o.append(s.charAt(i));
i++;
}
return new String(o);
}
public static void main(String[] args) {
System.out.println(nestedReplace("input [yes] [yes] [yes] [mk:[yes] [yes] [yes]] [yes] [iif:[yes] [yes] [yes]]"));
}
}
输出:
input Yes Yes Yes [mk:[yes] [yes] [yes]] Yes [iif:[yes] [yes] [yes]]
答案 1 :(得分:1)
尝试:
\[[^\[\]]+\[.+?][^\[\]]*\]|\[([a-z])[^\[\]]+\]
使用此选项可以匹配整个嵌套括号或非嵌套括号。然后,仅当Matcher
找到group(1)
(非嵌套括号)时才替换内容,例如:
public class Test {
public static void main(String[] args){
String[] strings = {"input [yes] [yes] [yes] [mk:[yes] [yes] [yes]] [yes] [iif:[yes] [yes] [yes]]",
"input [yes] [yes] [yes[yes] [yes] [yes] [mk:[yes] [yes] [yes]] [yes] [mk:[yes] [yes] [yes]] [yes] [iif:[yes] [yes] [yes]]",
"input [yes] [yes] [yes[yes] [yes] [yes] [mk:[yes] [yes] [yes]] [mk:[yes] [yes] [yes]] [yes] [iif:[yes] [yes] [yes]]"};
Pattern pattern = Pattern.compile("\\[[^\\[\\]]+\\[.+?][^\\[\\]]*\\]|\\[([a-z])[^\\[\\]]+\\]");
for(String string : strings) {
Matcher matcher = pattern.matcher(string);
while (true) {
if (matcher.find()) {
if (matcher.group(1) != null) {
string = string.substring(0, matcher.start(1)) + string.substring(matcher.start(1), matcher.end(1)).toUpperCase() + string.substring(matcher.end(1));
matcher.reset(string);
}
} else {
break;
}
}
System.out.println(string);
}
}
}
给出输出:
input [Yes] [Yes] [Yes] [mk:[yes] [yes] [yes]] [Yes] [iif:[yes] [yes] [yes]]
input [Yes] [Yes] [yes[yes] [yes] [yes] [mk:[yes] [yes] [yes]] [Yes] [mk:[yes] [yes] [yes]] [Yes] [iif:[yes] [yes] [yes]]
input [Yes] [Yes] [yes[yes] [yes] [yes] [mk:[yes] [yes] [yes]] [mk:[yes] [yes] [yes]] [Yes] [iif:[yes] [yes] [yes]]