文字列は次のとおりであると想定します。
The/at Fulton/np-tl County/nn-tl Grand/jj-tl
/
後に文字を削除し、以下のように出力するには
どうすればよいですか?The Fulton County Grand
ここでは、単純な正規表現ベースの置換が正常に機能するようです。
text = text.replaceAll("/\\S*", "");
ここで、\\S*
は「0個以上の非空白文字」を意味します。もちろん、他にも使用できるオプションがあります。
String input = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String clean = input.replaceAll("/.*?(?= |$)", "");
テストは次のとおりです。
public static void main( String[] args ) {
String input = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String clean = input.replaceAll("/.*?(?= |$)", "");
System.out.println( clean);
}
出力:
The Fulton County Grand
String text = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String newText = text.replaceAll("/.*?\\S*", "");
Java APIから:
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given replacement.
部分文字列または文字を置き換える必要がある場合は、最初の2つの方法を使用します。パターンまたは正規表現を置き換える必要がある場合は、2番目の2つの方法を使用します。
これは私のために働いた:
String text = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String newText = text.replaceAll("/.*?(\\s|$)", " ").trim();
収量:
フルトン郡グランド
/
これは基本的に、aの後に空白が続くか、文字列の終わりが続く文字を置き換えます。最後に、メソッドtrim()
によって追加された余分な空白に対応します。replaceAll
次のようにします。
startchar:置換する開始文字です。
endchar :置換するchich文字までの終了文字です。
"" :削除したいだけなので、空白に置き換えてください
string.replaceAll(startchar+".*"+endchar, "")
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29を参照してください
貪欲な数量詞の例も参照してください
作業例を参照してください
public static void main( String[] args ) {
String startchar ="/";
String endchar="?(\\s|$)";
String input = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl";
String clean = input.replaceAll(startchar+".*"+endchar, " ");
System.out.println( clean);
}
出力
The Fulton County Grand