[英]java regex replace special characters and spaces with dash
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库专门用于执行此操作,我会对它感兴趣,但是我不想使用pluss。
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.