【问题标题】:Remove special characters surrounded by white space删除被空格包围的特殊字符
【发布时间】:2014-04-26 21:47:14
【问题描述】:

如何删除侧面有空格的特殊字符。

String webcontent = "This is my string. i got this string from blabla.com."

当我使用这个正则表达式时

webcontent.replaceAll("[-.:,+^]*", "");

变成这样

String webcontent = "This is my string i got this string from blablacom"

我想要的不好

"This is my string i got this string from blabla.com"

【问题讨论】:

    标签: java regex web


    【解决方案1】:

    您必须使用前瞻(?=...)(后跟)来测试是否存在白色字符或字符串结尾:

    webcontent.replaceAll("[-.?:,+^\\s]+(?:(?=\\s)|$)", "");
    

    前瞻只是一个测试,不消耗字符。

    如果您想对所有标点字符执行相同操作,可以使用 unicode 标点字符类:\p{Punct}

    webcontent.replaceAll("[\\p{Punct}\\s+^]+(?:(?=\\s)|$)", "");
    

    (注意+ 和^ 不是标点符号。)

    【讨论】:

    • 如果点的开头像.This is my string. i got this string from blabla.com.
    • 感谢@Casimir et Hippolyte 和 anubhava 提供的干净利落的帮助。这个对我有用。我想知道(只是为了知识)如果字符串包含“?”怎么办?它自己,那么我们如何才能删除它,因为?正在帮助 char 正则表达式。我试过 .replaceAll("[.|:,+?]+(?!\\w)", "");但它不起作用。
    • @user1642500 使用转义 `\` 字符。
    • @user1642500 我已经在我的帖子中添加了它。只需将其移出[.|:,+?] 并使用[.|:,+]|\\?
    • @user1642500:在一个字符类中?没有特殊含义,所以你可以不用转义它:[-.:+?\\s]
    【解决方案2】:

    您可以使用负前瞻来避免这种情况:

    webcontent = webcontent.replaceAll("[-.:?,+^]+(?!\\w)", "");
    //=> This is my string i got this string from blabla.com
    

    【讨论】:

    • 感谢@anubhava 的帮助。我添加了关于删除的评论?特点。我们怎样才能做到这一点。
    • 那只需要在字符类中添加?。请参阅编辑后的答案。
    • 它应该可以在没有\\? 的情况下工作你的输入字符串是什么?
    【解决方案3】:

    试试这个

     // any one or more special characters followed by space or in the end
     // replace with single space
    
     webcontent.replaceAll("[-.:,+]+(\\s|$)", " ").trim();
    

    --编辑--

    如果特殊字符在开头

     webcontent.replaceAll("^([-.:,+]+)|[-.:,+]+(\\s|$)", " ").trim();
    

    输入:

    .This is my string. i got this string from blabla.com.        
    

    输出:

    This is my string i got this string from blabla.com
    

    --编辑--

    我也想替换?

    webcontent.replaceAll("^([-.:,+]+|\\?+)|([-.:,+]+|\\?+)(\\s|$)", " ").trim();
    

    输入

    ..This is my string.. ?? i got this string from blabla.com..
    

    输出

    This is my string  i got this string from blabla.com
    

    【讨论】:

      【解决方案4】:

      使用正则表达式[-.:?,+^](\s|$) 并使用基本字符串操作删除每个匹配项的字符。这是几行代码,但更干净。

      循环遍历所有特殊字符并检查下一个字符的纯 Java 解决方案也非常简单。

      一旦涉及前瞻/后瞻,为了清楚起见,我通常会回退到非正则表达式解决方案。

      【讨论】:

      • 其他特殊字符呢?
      • 如果点的开头像.This is my string. i got this string from blabla.com.
      • 您必须定义您不想替换的什么。 由空格包围的特殊字符 不足以描述您想要的内容。您拥有的异常越多,您的正则表达式或替换逻辑就越复杂。如果它适用于.,你可以让它适用于所有东西。
      • OK 不用担心。我现在明白了。我想我已经在我的帖子中添加了它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-12
      • 2021-10-16
      • 2014-08-17
      • 1970-01-01
      • 2020-03-16
      相关资源
      最近更新 更多