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”
答案 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(" ")) + "";