我有一个像
这样的文字字符串"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正则表达式是什么?
答案 0 :(得分:2)
(?:^| )[b-hj-z](?= |$)
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]
匹配除a
或i
(?= |$)
确定后面是空格或行尾的正面预测答案 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](?= |$)", "");
说明: