用相同数量的“。”替换正则表达式。作为它的长度

时间:2013-11-11 14:15:38

标签: java regex

请参阅我当前的尝试:http://regexr.com?374vg

我有一个正则表达式捕获我希望它捕获的内容,问题是String().replaceAll("regex", ".")只用一个.替换所有内容,如果它位于行尾,这很好,但是否则它不起作用。

如何用点替换匹配的每个字符,因此我得到与其长度相同数量的.符号?

5 个答案:

答案 0 :(得分:3)

这是一个单行解决方案:

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

答案 1 :(得分:1)

使用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点的字符串。

答案 2 :(得分:1)

考虑以下代码:

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 .........

答案 3 :(得分:1)

就个人而言,我会简化你的生活,只做这样的事情(对于初学者)。我会让你完成。

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
        }
    }
}

答案 4 :(得分:0)

你可以把你的正则表达式分组,所以用匹配分组长度的字符串替换它吗?类似的东西:

regex = (_what_i_want_to_match)
String().replaceAll(regex, create string that has that many '.' as length of $1)

注意:$ 1是您在搜索中匹配的内容

另见:http://www.regular-expressions.info/brackets.html