请参阅我当前的尝试:http ://regexr.com?374vg
我有一个正则表达式可以捕获我希望它捕获的内容,问题是它只String().replaceAll("regex", ".")
用一个替换所有内容,.
如果它位于行尾,这很好,但否则它不起作用。
如何用点替换匹配的每个字符,以便获得.
与其长度相同数量的符号?
请参阅我当前的尝试:http ://regexr.com?374vg
我有一个正则表达式可以捕获我希望它捕获的内容,问题是它只String().replaceAll("regex", ".")
用一个替换所有内容,.
如果它位于行尾,这很好,但否则它不起作用。
如何用点替换匹配的每个字符,以便获得.
与其长度相同数量的符号?
这是一个单行解决方案:
str = str.replaceAll("(?<=COG-\\d{0,99})\\d", ".").replaceAll("COG-(?=\\.+)", "....");
下面是一些测试代码:
String str = "foo bar COG-2134 baz";
str = str.replaceAll("(?<=COG-\\d{0,99})\\d", ".").replaceAll("COG-(?=\\.+)", "....");
System.out.println(str);
输出:
foo bar ........ baz
使用 String#replaceAll 是不可能的。您也许可以使用 Pattern.compile(regexp) 并像这样遍历匹配项:
StringBuilder result = new StringBuilder();
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(inputString);
int previous = 0;
while (matcher.find()) {
result.append(inputString.substring(previous, matcher.start()));
result.append(buildStringWithDots(matcher.end() - matcher.start()));
previous = matcher.end();
}
result.append(inputString.substring(previous, inputString.length()));
要使用它,您必须定义buildStringWithDots(int length)
构建一个包含length
点的字符串。
考虑这段代码:
Pattern p = Pattern.compile("COG-([0-9]+)");
Matcher mt = p.matcher("Fixed. Added ''Show annualized values' chackbox in EF Comp Report. Also fixed the problem with the missing dots for the positions and the problem, described in COG-18613");
if (mt.find()) {
char[] array = new char[mt.group().length()];
Arrays.fill(array, '.');
System.out.println( " <=> " + mt.replaceAll(new String(array)));
}
输出:
Fixed. Added ''Show annualized values' chackbox in EF Comp Report. Also fixed the problem with the missing dots for the positions and the problem, described in .........
就个人而言,我会简化你的生活,然后做这样的事情(对于初学者)。我会让你完成。
public class Test {
public static void main(String[] args) {
String cog = "COG-19708";
for (int i = cog.indexOf("COG-"); i < cog.length(); i++) {
System.out.println(cog.substring(i,i+1));
// build new string
}
}
}
你能把你的正则表达式放在分组中,然后用匹配分组长度的字符串替换它吗?就像是:
regex = (_what_i_want_to_match)
String().replaceAll(regex, create string that has that many '.' as length of $1)
?
注意:$1 是您在搜索中匹配的