Android 减少字符串替换长代码的方法

Android 减少字符串替换长代码的方法,android,regex,string,replace,Android,Regex,String,Replace,您好,这是我替换a字符的代码: string.replace("は", "b"); string.replace("ハ", "b"); 我想要的是使用OR运算符最小化代码 string.replace("は" || "ハ", "b"); 但它不起作用。是否有可能将上述第1个代码最小化?您可以提供一些代码或教程吗?您可以使用正则表达式 pattern = "([vb]a)"; string.replaceAll(pattern, "b"); 编辑 它应该以同样的方式工作,以便: patter

您好,这是我替换a字符的代码:

string.replace("は", "b");
string.replace("ハ", "b");
我想要的是使用OR运算符最小化代码

string.replace("は" || "ハ", "b");
但它不起作用。是否有可能将上述第1个代码最小化?您可以提供一些代码或教程吗?

您可以使用正则表达式

pattern = "([vb]a)";
string.replaceAll(pattern, "b");
编辑

它应该以同样的方式工作,以便:

pattern = "(は|ハ)";
string.replaceAll(pattern, "b");
或如下面一行所示:

string.replaceAll("(は|ハ)", "b");
string = string.replaceAll("[はハ]", "b");
有关正则表达式及其工作原理的良好教程,请参见此处。

一行:

String output = input.replaceAll("[vb]a","b");
有了新的输入,它将是:

string.replaceAll("(は|ハ)", "b");
string = string.replaceAll("[はハ]", "b");
第一个表达式称为“正则表达式”,这是表示字符串模式的一种非常强大的方法。这是最简单的一个。说明:

[]    indicates character class. Without a quantifier (?,*,+,{n,m}), it says
      "Match exactly one character from this list"
您可以将所有要替换的字符放在一个字符串中(不需要
|
字符)。我认为这是你所追求的最简洁的表现


它很值得研究正则表达式。请参阅上的优秀底漆。你可以在

上练习看看正则表达式<代码>([vb])a将被
b
替换嗨,我刚刚再次编辑了我的代码。