I have got a 开发者_如何转开发string containing an address and I want to remove the post code which is the last 2 words.
eg 21 Lane Street London W10 2GH
I want 'W10 2GH' removed
Replace the pattern \s*\w+\s+\w+$
with an empty String:
String s = "21 Lane Street London W10 2GH";
System.out.println(s.replaceFirst("\\s*\\w+\\s+\\w+$", ""));
produces:
21 Lane Street London
A short explanation:
\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
Lots of ways. The easiest in this situation is just use rindex()
lastIndexOf()
to find the blanks.
It might be a bit safer and stronger to use a regular expression to search for actual post codes.
精彩评论