以下のような着信文字列があります。
Sample ("Testing")
("Testing")
部分文字列をに置き換える必要があり"Testing"
ます。基本的に、左右の括弧を削除する必要があります。
Javaで同じことを行うためのポインタを提供してください。
不必要な正規表現チェックのアプローチ:
String newstring = sample.replaceAll("\\(", "");
newstring = newstring.replaceAll("\\)", "");
System.out.println(newstring);
より良いアプローチ(正規表現チェックなし、直接部分文字列チェック):
String newstring = sample.replace("(", "");
newstring = newstring.replace(")", "");
System.out.println(newstring);
部分文字列法を使用した別のアプローチ:
String newstring=sample.substring(0,sample.indexOf('('))+sample.substring(sample.indexOf('(')+1,sample.lastIndexOf(')'));
編集: 括弧内に「テスト」がある場合にのみ括弧を削除するには、次のコードに従います。
String newstring = sample.replace("(\"Testing\")","\"Testing\"");
正規表現チェック方法:
String newstring=sample.replaceAll("(\\()(?=(\"Testing\"))","");
newstring = newstring.replaceAll("(?<=(\"Testing\"))\\)","");
しかし、常識的には、次のようにする必要があります。
if(sample.equals("Sample (\"Testing\")")
sample="Sample \"Testing\"";
置換機能について説明するこの短いチュートリアルを使用できます。