开发者

How can I remove the last 2 words in a string?

开发者 https://www.devze.com 2023-02-12 09:13 出处:网络
I have got a 开发者_如何转开发string containing an address and I want to remove the post code which is the last 2 words.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号