正则表达式删除字符串中的最后一个单词?

时间:2012-11-27 09:21:05

标签: java

I have a string like this "87 CAMBRIDGE PARK DR".I have used the below regular expression 
to remove the last word "DR", but it also removing the word "PARK" also..

以下是我的代码......

String regex = "[ ](?:dr|vi|tes)\\b\\.?"; /*regular expression format*/

String inputString ="87 CAMBRIDGE PARK DR"; /*input string */

Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(inputString);
            inputString = matcher.replaceAll("");     

Now the out put is "87 CAMBRIDGE"..

但是我需要输出为“87 CAMBRIDGE PARK”

2 个答案:

答案 0 :(得分:2)

尝试以下REGEX:

            String inputString ="87 CAMBRIDGE PARK DR";
        System.out.println(inputString.replaceAll("\\w+$", ""));

输出: 87坎布里奇公园

打破上述正则表达式:

"\\w+$"

-check如果该行的结尾后跟几个单词字符。

另外,如果您确定最后一个单词只是大写(块)字母。

    System.out.println(inputString.replaceAll("[A-Z]+$", ""));

答案 1 :(得分:1)

你可以按照以下方式实现:

String inputString ="87 CAMBRIDGE PARK DR"; /*input string */
System.out.println(inputString.replaceFirst("\\s+\\w+$", ""));

正则表达式理解

\s+  : one or more white space characters

\w+  : one or more alpha-numerics 

$    : the end of the input

另一种方式如下:

 String inputString ="87 CAMBRIDGE PARK DR"; /*input string */
inputString = inputString.substring(0, inputString.lastIndexOf(" ")) + "";
相关问题