用于删除字符串

时间:2018-01-04 20:14:25

标签: java regex

我有一个像

这样的文字字符串
"there i r u w want to y z go because f g of a matter"

我想删除除“a”和“i”之外的所有单个字母。 所以上面给出的示例字符串就像

there i want to go because of a matter

除了“a”和“i”之外,删除所有这些单个字母的java正则表达式是什么?

2 个答案:

答案 0 :(得分:2)

代码

See regex in use here

(?:^| )[b-hj-z](?= |$)

用法

See code in use here

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        final String regex = "(?:^| )[b-hj-z](?= |$)";
        final String string = "there i r u w want to y z go because f g of a matter";
        final String subst = "";

        final Pattern pattern = Pattern.compile(regex);
        final Matcher matcher = pattern.matcher(string);

        // The substituted value will be contained in the result variable
        final String result = matcher.replaceAll(subst);

        System.out.println("Substitution result: " + result);
    }
}

如果您需要不区分大小写的匹配,请将Pattern.CASE_INSENSITIVE传递给Patter.compile

结果

输入

there i r u w want to y z go because f g of a matter

输出

there i want to go because of a matter

说明

  • (?:^| )在行首处断言位置或按字面匹配空格
  • [b-hj-z]匹配除ai
  • 以外的任何小写ASCII字母
  • (?= |$)确定后面是空格或行尾的正面预测

答案 1 :(得分:0)

使用示例代码删除除“a”和“i”之外的所有单个字母

String resultStr = "there i r u w want to y z go because f g of a matter".replaceAll("(?:^| )[b-hj-z | B-HJ-Z](?= |$)", "");

说明:

Spring Boot sample project about Profiles showcasing