我需要一个人帮我解决这个问题,我想用Drive Road和Street替换Dr,Rd和St等角色,使用正则表达式,请问这怎么办?我已经尝试了很多方法,但我的结果是对的。 例如,如果用户为变量vaddress提供此地址: 13,克林顿击败艾伦女王博士。 结果应该是 13,克林顿街关闭艾伦路的女王驾驶。
这是我的代码示例:
public void standardizeAddress(String vaddress){
address = vaddress;//address is an instance variable
String str1,str2;
//Replace all instances of 'St,Rd,Dr' with 'Street,Road and Drive' Using
String regex = "\\sSt\\s";
Pattern pat = Pattern.compile(regex);
Matcher match = pat.matcher(address);
while(match.find())
address = match.replaceAll(" Street ");
System.out.println(address);
str1 = address;
regex = "\\sRd\\s";
pat = Pattern.compile(regex);
match = pat.matcher(str1);
while(match.find())
str1 = match.replaceAll(" Road ");
System.out.println(str1);
str2 = str1;
regex = "\\sDr\\s";
pat = Pattern.compile(regex);
match = pat.matcher(str2);
while(match.find())
str2 = match.replaceAll(" Drive ");
System.out.println(str2);
}
提前谢谢
答案 0 :(得分:2)
这应该有效:
String str = "Dr abc Rd def St ghi";
str = str.replaceAll("(\\s+|^)Dr(\\s+|$)", "$1Drive$2");
str = str.replaceAll("(\\s+|^)Rd(\\s+|$)", "$1Road$2");
str = str.replaceAll("(\\s+|^)St(\\s+|$)", "$1Street$2");
System.out.println(str);
收益率:
驾驶abc Road def Street ghi
此代码应在您要替换的单词之前保留空格。
答案 1 :(得分:1)
我认为如果您的情况非常简单并且您的方案很小(并且您不需要复杂的正则表达式),则可以使用String.replaceAll或String.replace。
答案 2 :(得分:0)
如果您想使用Matcher,以下代码示例将帮助您:)
String address = "St number 9 and St number 99 and st number 999";
String regex = "\\bSt\\b";
Pattern pat = Pattern.compile(regex);
Matcher match = pat.matcher(address);
address = match.replaceAll("Street");
System.out.println(address);
输出结果:Street number 9 and Street number 99 and st number 999
答案 3 :(得分:0)
只是为了展示Pattern和Matcher的用法。我认为几个replaceAll的简单答案最具可读性。
Map<String, String> replacements = new LinkedHashMap<>(); // Keep in order
replacements.put("Dr", "Drive");
replacements.put("Rd", "Road");
replacements.put("St", "Street");
StringBuilder regex = new StringBuilder();
for (String abbrev : replacements.keySet()) {
regex.append(regex.length() == 0? "\\b(" : "|");
regex.append(Pattern.quote(abbrev));
}
regex.append(")\\b");
Pattern abbrevPattern = Pattern.compile(regex.toString());
Matcher m = abbrevPattern.matcher(vaddress);
StringBuffer result = new StringBuffer();
while (m.find()) {
String outwritten = replacements.get(m.group(1));
m.appendReplacement(result, outwritten);
}
m.appendTail(result);
return result.toString();