[英]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.