使用正则表达式替换所有奇数出现的子字符串

时间:2018-05-30 05:51:39

标签: java regex string

我有一个字符串~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~

我想替换子串的奇怪出现' ~~'即第1,第3 ..用另一根字符串' **'。

我的输出应为**40~~ Celsius Temp: 33 Celsius Temp:**50~~

如何使用Java中的regex实现这一目标?

4 个答案:

答案 0 :(得分:1)

你真的需要一个基本的解析器来处理这个问题;正则表达式不是为计算这样的事件而设计的。下面代码的逻辑很简单。每当我们点击一​​场比赛~~时,我们会做两件事之一。如果它是奇怪的,那么我们将空字符串附加到替换,否则我们将重新匹配我们匹配的~~

String input = "~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~";
Pattern p = Pattern.compile("~~");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer(input.length());
int i = 0;

while (m.find()) {
    if (i % 2 == 0) {
        m.appendReplacement(sb, "**");
    }
    else {
        m.appendReplacement(sb, m.group(0));
    }
    ++i;
}
m.appendTail(sb);
System.out.println(sb.toString());

**40~~ Celsius Temp: 33 Celsius Temp:**50~~

Demo

答案 1 :(得分:0)

我认为对于你的问题陈述,你不需要搜索奇怪的事件,从它显示的例子中,你需要用**(数字)替换~~(数字)并忽略其他格式的~~ .. < / p>

答案 2 :(得分:0)

有些人已经提出类似的解决方案,但仍然:

String org = "~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~";
String rep = org.replaceAll("~~(\\d)","**$1");

在此处,~~(\d)会搜索~~后跟数字,并替换为**,以使用$1

保留第一个数字

答案 3 :(得分:-2)

如果~~严格成对出现,您可以使用替换捕获组。

private final static Pattern pattern = Pattern.compile("(?:~~([^~]+~~))");

public static String replaceOddTildes(String value) {
    return pattern.matcher(test).replaceAll("**$1");
}

String result = replaceOddTildes("~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~"));

请注意,如果它们不在匹配对中,它将错过最后一组奇数:

replaceOddTildes("An ~~un~~ paired ~~example!").equals("An **un~~ paired ~~example!")`

如果这就是你想要一个不匹配的一对被处理的方式,那么那很好。

详细模式:

(?:             a non-capturing group, consisting of
    ~~          a pair of tildes, followed by
    (           a capturing group, consisting of
    [^~]+       one or more characters that is not a tilde, followed by
    ~~          a pair of tildes
    )           end of the capturing group
)               end of the non-capturing group

匹配的替换是一对星号,后跟捕获组的内容。

相关问题