【问题标题】:Remove specific word nested in multiple html tags by regex通过正则表达式删除嵌套在多个 html 标记中的特定单词
【发布时间】:2019-11-26 08:08:20
【问题描述】:

我想从 html 中删除特定的单词。我正在将 HTML 处理为 java 中的字符串。该词必须嵌套在特定标签中。我想删除.wrapper,只有当它在<template><style>里面时,我不想删除html中的所有.wrappers

我已尝试通过正则表达式将单词替换为空字符串,但它不能按我的需要工作。我错过了一些东西,无法弄清楚是什么。

要处理的字符串:

String input = "<div><template><div><style>.wrapper #popup-popupTemplate1 .popup-content { width: 800px; height: 300px }</style></div></template><div>"

所需的输出(删除特定的单词,.wrapper):

String output = "<div><template><div><style>#popup-popupTemplate1 .popup-content { width: 800px; height: 300px }</style></div></template><div>"

这对我不起作用,但在在线正则表达式调试器中,这个正则表达式选择我需要的单词。

String result = input.replaceAll("<template>.*?<style>.*?(\\.wrapper).*?<\\/style>.*?<\\/template>", "");

【问题讨论】:

  • 我假设 replaceAll() 替换了您的完整匹配项,而不仅仅是 .wrapper 所在的捕获组。您可以将使用代码获得的输出添加到您的问题中吗?
  • 您是否尝试过使用 JSoup 或类似方法沿着 DOM 树向下移动到 &lt;style&gt; 元素,然后使用正则表达式,而不是尝试使用单个正则表达式来统治它们?

标签: java html regex


【解决方案1】:
  • “技巧”是使用\K--> INFO <--

  • 还深入了解惰性 ? 的作用。

正则表达式:&lt;template&gt;.*?&lt;style&gt;.*?\K\.wrapper

https://regex101.com/r/ldnoFx/1

【讨论】:

  • 嗯,它在代码中对我不起作用,但在您发送的在线正则表达式调试器中,它似乎没问题。
  • 当我在这个在线调试器中测试它时,它也不起作用。 regexplanet.com/cookbook/…我注意到了,你发送的那个链接是为PHP配置的,会不会有这个问题?
  • 这对你有用吗? (?!&lt;template&gt;.*?&lt;style&gt;.*?)\.wrapper
  • 这会选择.wrapper,即使它没有嵌套在&lt;template&gt;&lt;/template&gt;&lt;style&gt;&lt;/style&gt;
  • 看看你能不能用Java获得PCRE :)
【解决方案2】:

您需要检查将原始字符串 (s1) 中的匹配字符串 (matched) 替换为更改后的字符串 (replacedString) 的方法。

import java.util.regex.*;

    public class ReplaceExample { 

    public static void main(String args[]){  

    String s1 ="<div><template><div><style>.wrapper #popup-popupTemplate1 .popup-content { width: 800px; height: 300px }</style></div></template><div>"; 

    Pattern pattern = Pattern.compile("<template>(.*?)</template>");

    Matcher matcher = pattern.matcher(s1);

    if (matcher.find())
    {
        String matched = matcher.group(1);
        String replacedString = matched.replaceAll("(.wrapper)+","");        
        System.out.println(replacedString); 
    } 

    }

    }

【讨论】:

    猜你喜欢
    • 2014-12-11
    • 2018-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    相关资源
    最近更新 更多