-1

请我需要一些人来帮助我解决这个问题,我想使用正则表达式将 Dr、Rd 和 St 等字符替换为 Drive Road 和 Street,请问该怎么做?我已经尝试了很多方法,但我的结果是不正确的。例如,如果用户为变量 vaddress 提供此地址:13, Clinton str off allen rd queens dr。结果应该是 13 号,Clinton Street off allen Road Queens Drive。

这是我的代码示例:

    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);    
        }

先感谢您

4

4 回答 4

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 路 def 街 ghi

此代码也应在您要替换的单词之前保留空格。

于 2013-02-15T09:17:26.620 回答
1

我认为如果您的情况非常简单并且您的场景很小(并且您不需要复杂的正则表达式),您可以简单地使用String.replaceAllString.replace

于 2013-02-15T09:19:52.433 回答
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

于 2013-02-15T09:25:56.963 回答
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();
于 2013-02-15T09:31:56.860 回答