查找要排除的子然后暂时删除它的空间。一旦整个字符串已被拆分,找到之前编辑过的子字符串,然后将其替换为原来的空格。
// let's say:
// whole = "The city of San Francisco is truly beautiful!",
// token = "San Francisco"
public static String[] excludeString(String whole, String token) {
// replaces token string "San Francisco" with "SanFrancisco"
whole = whole.replaceAll(token, token.replaceAll("\\s+", ""));
// splits whole string using space as delimiter, place tokens in a string array
String[] strarr = whole.split("\\s+");
// brings "SanFrancisco" back to "San Francisco" in strarr
Collections.replaceAll(Arrays.asList(strarr), token.replaceAll("\\s+", ""), token);
// returns the array of strings
return strarr;
}
使用范例:
public static void main(String[] args) {
String[] arr = excludeString("The city of San Francisco is truly beautiful!", "San Francisco");
System.out.println(Arrays.asList(arr));
}
比方说,你的字符串是:"The city of San Francisco is truly beautiful!"
结果将是: [The, city, of, San Francisco, is, truly, beautiful!]
你不能用一个正则表达式准确地做到这一点...正则表达式匹配字符的模式,而不是地方的名称。这是图书馆的用途。 – Radiodef
@Radiodef我同意正则表达式不是这样做的正确方法,但我发布了正则表达式答案:) –
正则表达式在Java中有很多性能问题,如此处所述https://eyalsch.wordpress.com/2009/05/21/regex /。你甚至可以在我的答案中找到3个词组或短语。只是说;) –