【问题标题】:Use regex to remove all special characters from string using thymeleaf使用 regex 使用 thymeleaf 从字符串中删除所有特殊字符
【发布时间】:2019-05-20 06:40:39
【问题描述】:

我是 thymeleaf 的新手,最近我部分弄清楚了如何从字符串中删除特殊字符。以下代码有效,但我必须替换每个特殊字符。

${#strings.toLowerCase(#strings.replace(#strings.replace(#strings.replace(name, '''','-'), '&',''),' ','-'))}

有什么办法可以让我使用单个正则表达式通过 thymeleaf 从字符串中删除所有特殊字符?

【问题讨论】:

  • 在您的示例中,哪些字符被称为“特殊字符”? (只是 ''''、'-' 还是全部?)
  • 数字呢?
  • 所有特殊字符以及数字。例如,我们可以使用 '/[^A-Za-z0-9\-]/' 表达式来删除所有特殊字符。

标签: regex thymeleaf special-characters


【解决方案1】:

Java Strings 已经有了用正则表达式替换的方法:string.replaceAll('...', '...')。在你的情况下,你可以简单地做:

${#strings.toLowerCase(name.replaceAll('[^A-Za-z0-9\-]', ''))}

【讨论】:

    【解决方案2】:

    尝试使用如下代码:

    Regex regex1 = new Regex(@"[^A-Za-z0-9]");
    strings.replace(name, "", regex1.match(name));
    

    祝你好运!

    【讨论】:

    • 我正在尝试对以下 HTML sn-p 进行更改:
    猜你喜欢
    • 2014-02-22
    • 2011-09-27
    • 2012-12-16
    • 1970-01-01
    • 2012-05-04
    • 2016-08-23
    • 2017-03-16
    • 2021-06-01
    相关资源
    最近更新 更多