java - 使正则表达式更加动态

标签 java regex

我几周前发布了这个问题,涉及使用 Java 中的正则表达式提取捕获组,Extracting Capture Group Using Regex ,我收到了有效的答案。几周前我还发布了这个问题,涉及使用正则表达式在 Java 中进行字符替换,Replace Character in Matching Regex ,并收到了一个更好的答案,比我从第一篇文章中得到的答案更有活力。我将通过示例快速说明。我有一个像这样的字符串,我想从中提取“ID”:

String idInfo = "Any text up here\n" +
                "Here is the id\n" +
                "\n" +
                "?a0 12 b5\n" +
                "&Edit Properties...\n" +
                "And any text down here";

在这种情况下,我希望输出为:

a0 12 b5

但事实证明,ID 可以是任意数量的八位字节(只需是 1 个或多个八位字节),并且我希望我的正则表达式能够基本上解释 1 个八位字节的 ID,然后是任意数量的后续八位字节(从 0 到任意多个)。我在“匹配正则表达式中的替换字符”帖子中收到答案的人针对我的一个类似但不同的用例执行了此操作,但我在将这个“更动态”的正则表达式移植到第一个用例时遇到了麻烦。

目前,我有...

Pattern p = Pattern.compile("(?s)?:Here is the id\n\n\\?([a-z0-9]{2})|(?<!^)\\G:?([a-z0-9]{2})|.*?(?=Here is the id\n\n\\?)|.+");
Matcher m = p.matcher(certSerialNum);
String idNum = m.group(1);
System.out.println(idNum);

但是它抛出了异常。此外,我实际上希望它使用模式中所有已知的相邻文本,包括“这是 id\n\n\?”和“\n&编辑属性...”。我需要进行哪些修正才能使其正常工作?

最佳答案

看起来你想要这样的东西,

String idInfo = "Any text up here\n" +
        "Here is the id\n" +
        "\n" +
        "?a0 12 b5\n" +
        "&Edit Properties...\n" +
        "And any text down here";
Pattern regex = Pattern.compile("Here is the id\\n+\\?([a-z0-9]{2}(?:\\s[a-z0-9]{2})*)(?=\\n&Edit Properties)");
Matcher matcher = regex.matcher(idInfo);
while(matcher.find()){
        System.out.println(matcher.group(1));
}

输出:

a0 12 b5

DEMO

关于java - 使正则表达式更加动态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27066583/

相关文章:

python - 删除 <select> 元素的正则表达式

c# - 使用正则表达式为特殊字符添加前缀

java - Storm 与卡夫卡 : Increasing amount of open file descriptors

java - Apache Commons Net API 使用

java - 在 Java 中实现和修复递归方法

java - 在 java 中的 lang.properties 中存储印地语并检索它

java - 用于 JUnit 测试的模拟对象

c++ - 你如何打印 std::regex?

javascript - 使用 jQuery 防止 html 输入中的值

php - 正则表达式获取括号之间有文本的括号之间的文本