【问题标题】:Extract String from a within a String using a Regular Expression使用正则表达式从字符串中提取字符串
【发布时间】:2014-10-17 08:28:46
【问题描述】:


我有一个非常大的字符串,其中包含一些标记,例如:

{codecitation class="brush: java; gutter: true;" width="700px"}

我需要收集长字符串中包含的所有标记。我在这个任务中发现的困难是标记都包含不同的参数值。他们唯一的共同点是开头的部分:

{codecitation class="brush: [VARIABLE PART] }

您对使用正则表达式收集 Java 中的所有标记有什么建议吗?

【问题讨论】:

  • 它看起来像一个 json 文件。你为什么不为此使用解析器?
  • @AvinashRaj 这是 HTML 或 XML 而不是 JSON。
  • Java 有一个优秀的内置 XML 解析器,并且有几个 HTML 解析器可用。尝试为此使用正则表达式会让您感到悲伤。说真的,使用解析器。

标签: java regex


【解决方案1】:

使用模式匹配来查找如下标记。我希望这会有所帮助。

String xmlString = "{codecitation class=\"brush: java; gutter: true;\" width=\"700px\"}efasf{codecitation class=\"brush: java; gutter: true;\" width=\"700px\"}";
Pattern pattern = Pattern.compile("(\\{codecitation)([0-9 a-z A-Z \":;=]{0,})(\\})");
Matcher matcher = pattern.matcher(xmlString);

while (matcher.find()) {
    System.out.println(matcher.group());
}

【讨论】:

    【解决方案2】:

    我猜你对 brush: java;gutter: true; 部分特别感兴趣。

    也许这个 sn-p 有帮助:

    package test;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class CodecitationParserTest {
    
        public static void main(String[] args) {
            String testString = "{codecitation class=\"brush: java; gutter: true;\" width=\"700px\"}";
            Pattern codecitationPattern = Pattern
                    .compile("\\{codecitation class=[\"]([^\"]*)[\"][^}]*\\}");
            Matcher matcher = codecitationPattern.matcher(testString);
    
            Pattern attributePattern = Pattern
                    .compile("\\s*([^:]*): ([^;]*);(.*)$");
            Matcher attributeMatcher;
            while (matcher.find()) {
                System.out.println(matcher.group(1));
                attributeMatcher = attributePattern.matcher(matcher.group(1));
                while (attributeMatcher.find()) {
                    System.out.println(attributeMatcher.group(1) + "->"
                            + attributeMatcher.group(2));
                    attributeMatcher = attributePattern.matcher(attributeMatcher
                            .group(3));
                }
            }
        }
    
    }
    

    codecitationPattern 提取代码引用元素的类属性的内容。 attributePattern 提取第一个键和值以及其余部分,因此您可以递归地应用它。

    【讨论】:

    • 实际上我还需要收集其他参数的信息,但无论如何感谢您的时间。
    猜你喜欢
    • 2014-08-25
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    相关资源
    最近更新 更多