我有一个包含地址的字符串,我想删除最后 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
关于java - 如何删除字符串中的最后 2 个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5080155/