有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java删除被空格包围的特殊字符

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

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"

共 (4) 个答案

  1. # 1 楼答案

    试试这个

     // 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
    
  2. # 2 楼答案

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

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

    前瞻只是一个测试,不使用字符

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

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

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

  3. # 3 楼答案

    使用regex[-.:?,+^](\s|$)并通过基本字符串操作删除每个匹配的字符。代码多了几行,但要干净得多

    在纯java解决方案中,循环所有特殊字符并检查下一个字符也是非常简单的

    一旦涉及lookahead/lookbehind,为了清晰起见,我通常采用非正则表达式的解决方案

  4. # 4 楼答案

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

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