有 Java 编程相关的问题?

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

html Java正则表达式在关闭标记后添加空格(如果不存在)

我有下面的html字符串,我想在所有标记后面添加空格,比如</strong>,其中缺少空格,只在主体内部。如果已经有空间,则不应添加额外空间

<html><head><title>test</title></head><body>This <strong>Super</strong> subject can be <strong>super</strong>test into object</body></html>

应将其转换为以下内容:

<html><head><title>test</title></head><body>This <strong>Super</strong> subject can be <strong>super</strong> test into object</body></html>

使用正则表达式是否可行?你能帮我学一下正则表达式吗


共 (1) 个答案

  1. # 1 楼答案

    您可以使用这个正则表达式,它将查找后面没有空格的任何结束标记(形式为</zzzz>),然后用$1替换它:

    (<\/[a-z]+>)(?! )
    

    Demo on regex101

    这将修改HTML中的任何结束标记。为了只修改^ {< CD3> }中的结束标记,可以先将字符串拆分到^ { }和字符串的平衡,然后只修改中间部分。比如说,

    String s = "<html><head><title>test</title></head><body>This <strong>Super</strong> subject can be <strong>super</strong>test into object</body></html>";
    String [] pieces = s.split("</?body");
    pieces[1] = pieces[1].replaceAll("(</[a-z]+>)(?! )", "$1 ");
    s = pieces[0] + "<body" + pieces[1] + "</body" + pieces[2];
    System.out.println(s);
    

    输出:

    <html><head><title>test</title></head><body>This <strong>Super</strong> subject can be <strong>super</strong> test into object</body></html>