[英]How can I remove the last 2 words in a string?
我有一個包含地址的字符串,我想刪除最后2個字的郵政編碼。
例如21 Lane Street London W10 2GH
我想刪除'W10 2GH'
用空字符串替換模式\\s*\\w+\\s+\\w+$
:
String s = "21 Lane Street London W10 2GH";
System.out.println(s.replaceFirst("\\s*\\w+\\s+\\w+$", ""));
生產:
21 Lane Street London
一個簡短的解釋:
\s* # zero or more white space chars
\w+ # one or more alpha-nums (or underscore), specifically: [a-zA-Z0-9_]
\s+ # one or more white space chars
\w+ # one or more alpha-nums (or underscore)
$ # the end of the input
很多方法。 在這種情況下最簡單的方法是使用
rindex()
lastIndexOf()
來查找空白。
使用正則表達式搜索實際的郵政編碼可能會更安全一些。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.