3

假设字符串是:

The/at Fulton/np-tl County/nn-tl Grand/jj-tl

如何删除字符后/和输出如下 The Fulton County Grand

4

5 回答 5

8

看起来一个简单的基于正则表达式的替换在这里可以正常工作:

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

这里的\\S*意思是“0个或多个非空白字符”。当然,您也可以使用其他选项。

于 2012-07-16T07:16:14.163 回答
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
于 2012-07-16T07:16:23.870 回答
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.

如果您需要替换子字符串或字符,请使用 1st 2 方法。如果您需要替换模式或正则表达式,请使用 2nd 2 方法。

于 2012-07-16T07:15:51.853 回答
1

执行以下操作:

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
于 2012-07-16T07:17:26.940 回答
1

这对我有用:

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

产量:

富尔顿县大酒店

这基本上替换了 a 之后的任何字符,/并且后跟空格或字符串末尾。最后trim()是为了迎合该方法添加的额外空白replaceAll

于 2012-07-16T07:21:24.647 回答