Java replaceAll()正则表达式不起作用 [英] Java replaceAll() regex does not work

查看:945
本文介绍了Java replaceAll()正则表达式不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用%替换所有特殊字符,例如:

I'm trying to replace all special characters with a "%", like:

"123.456/789" -> "123%465%798"

我的正则表达式是:

[^a-zA-Z0-9]+

在线工具*它完全有效,但在java中

In online tools* it works perfecly, but in java

s.replaceAll("[^a-zA-Z0-9]+", "%");

字符串保持不变。

* I试过: http://www.regexplanet.com/ http://regex101.com/ 和其他人

*I tried: http://www.regexplanet.com/ http://regex101.com/ and others

推荐答案

字符串是不可变的。您忘了将新的 String 重新分配给 s 变量:)

Strings are immutable. You forgot to reassign new String to the s variable :)

s = s.replaceAll("[^a-zA-Z0-9]+", "%");
 // ^ this creates a new String

这篇关于Java replaceAll()正则表达式不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆