2012-07-16 122 views

回答

8

它看起來像一個簡單的正則表達式爲基礎的替換可能在這裏工作精細:

text = text.replaceAll("/\\S*", ""); 

這裏\\S*指「0個或多個非空白字符」。當然,您還可以使用其他選項。

2
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. 

如果你需要替換一個子串或一個cha使用前2種方法。 如果您需要替換模式或正則表達式,請使用第2種方法。

+0

呵呵?這個怎麼用?你測試了輸出嗎? (提示:它不起作用) – Bohemian 2012-07-16 07:16:57

+0

這根本不適合我。 – 2012-07-16 07:17:05

+3

這將只刪除斜線,OP要刪除斜線後面的字符。 – npinti 2012-07-16 07:17:20

5
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 
1

做如下:

STARTCHAR:是要替換起始字符。

endchar:是一個結尾字符,直到您要替換的奇奇字符。

「」:是因爲你只是想刪除它以空格

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

所以更換也看到greedy quantifier examples

看到工作示例

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 
+0

我知道爲什麼downvote? – 2012-07-16 07:22:39

1

這爲我工作:

String text = "The/at Fulton/np-tl County/nn-tl Grand/jj-tl"; 
String newText = text.replaceAll("/.*?(\\s|$)", " ").trim(); 

產量:

的富爾頓縣大

這基本上取代了它們之後的任何字符(S)一個/並且後面跟着一個空白區域,否則,在字符串的末尾。最後的trim()是爲了迎合由replaceAll方法增加的額外空白空間。

相關問題