我正在尝试从邮寄地址中删除街道号码。
我在 Java 中有一个正则表达式:
address.replace("^\\s*[0-9]+\\s+","");
它适用于这个地址:
301 West 23rd Street
制作:
West 23rd Street
但是当我把它应用到这个地址时,地址没有改变:
70-50 69th Place
相反,它需要:
69th Place
有什么想法吗?
最佳答案
您的正则表达式与该字符串不匹配。这里是正则表达式的解释
^ Start of string. Matches successfully. \\s* Zero or more whitespace. Matches the empty string. [0-9]+ One or more digits. Matches "70". \\s+ One or more whitespace. Fails to match.
The character after "70" is a hyphen and a hyphen is not a whitespace character so the match fails and no replacement is made. To fix it you can put a hyphen in the character class:
address = address.replace("^\\s*[0-9-]+\\s+", "");
当连字符位于字符类中时,它具有特殊含义(字符范围),但以下两种情况除外:
- 当它在字符类的开头或结尾时
- 使用反斜杠转义时(但请注意,Java 字符串文字中需要两个反斜杠)。
关于java - 为什么这个 Java 正则表达式在从美国街道地址中去除街道号码时工作不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3703832/