开发者

How do I make this regex a valid Java regex?

In an earlier question I asked about sanitizing postal street addresses, one of the respondents recommended this solution:

addressString.replace(/^\s*[0-9]+\s*(?=.*$)/,'');

which is perhaps a valid regex call but is not valid in Java.

开发者_StackOverflow中文版

I unsuccessfully tried to make this valid Java code by changing it to the following:

addressString.replaceAll("/^\\s*[0-9]+\\s*(?=.*$)/","")

But this code had no effect on the address I tested it with:

310 W 50th Street

Did I not correctly translate this to Java?


You don't need the slashes in Java.

addressString.replaceAll("^\\s*[0-9]+\\s*(?=.*$)","")


You need to take out the slashes at the beginning and end:

addressString.replaceAll("^\\s*[0-9]+\\s*(?=.*$)","")

They're used to quote regexes in some languages, but Java just uses ""


You need to get rid of the forward slashes at the beginning and end.

For the future, you can probably ask for clarification on the answer itself instead of starting a new question. I apologize, I was going to ask the person who gave that answer to translate it to valid Java myself but forgot.


Edited to support street names that start with a number:

Try the following Java String:

"^\\s*[0-9]+\\s*(?=.*$)". 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜