java java正则表达式用破折号替换特殊字符和空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28142947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java regex replace special characters and spaces with dash
提问by Code Junkie
I have the following string,
我有以下字符串,
String model = "Town & Country";
I'd like to replace the special characters and the spaces with a dash as well as lower case it for a nice clean url.
我想用破折号和小写替换特殊字符和空格,以获得一个干净的网址。
Example
例子
"town-country"
I've tried the following code.
我试过下面的代码。
"Town & Country".replaceAll("[^A-Za-z0-9]", "-").toLowerCase();
but I ended up with the following output.
但我最终得到了以下输出。
town---country
Could someone assist me with the regex so that this works properly? I if there is multiple spaces, I'd like to reduce it to a single space replaced by a dash. If there is a good java library out there designed to do this, I'd be interested in it, however I do not want to use pluses.
有人可以帮助我使用正则表达式以使其正常工作吗?如果有多个空格,我想将其减少为用破折号代替的单个空格。如果有一个很好的 Java 库可以做到这一点,我会对它感兴趣,但是我不想使用加号。
回答by Alexis King
You're close, you just need to add a quantifier to the expression to allow it to match more than one character.
你很接近,你只需要在表达式中添加一个量词,以允许它匹配多个字符。
/[^A-Za-z0-9]+/
(Note the +
at the end.)
(注意+
最后。)
So, your code should be this:
所以,你的代码应该是这样的:
"Town & Country".replaceAll("[^A-Za-z0-9]+", "-").toLowerCase();