简体   繁体   English

使用正则表达式解析正则表达式

[英]Parse regex with regex

I have pattern [a-z0-9]{9}|[a-z0-9]{11}我有模式[a-z0-9]{9}|[a-z0-9]{11}

Here, I have to parse that regex to get 9 and 11 for future message that "U have to input 9 or 11 symbols"在这里,我必须解析该正则表达式以获得 9 和 11 以备将来“您必须输入 9 或 11 个符号”的消息

Also I have regex like我也有正则表达式

[a-z0-9]{9}

[a-z0-9]{9,}

[a-z0-9]{9,11}

I need to write some method,which can parse all that strings to get Number of available symbols.我需要编写一些方法,它可以解析所有字符串以获取可用符号的数量。

I did我做了

Pattern.compile(".*\\\\{(\\\\d+)(,?)(\\\\d*)\\\\}(\\\\|.*\\\\{(\\\\d+)\\\\})?");

It find only last number in my first pattern.它只在我的第一个模式中找到最后一个数字。 But other don't recognize.但其他不认识。

How to check all strings?如何检查所有字符串?

Upd: I can not understand, but in Java first pattern from answer \\{(\\d+)(?:,(\\d*))?\\} doesn't match but find 3 my strings.更新:我不明白,但在 Java 第一个模式中,答案\\{(\\d+)(?:,(\\d*))?\\}不匹配,但找到 3 个我的字符串。 But first and the longest string it doesn't find.但是它没有找到第一个和最长的字符串。

What is different between matches and find?匹配和查找有什么区别? And why that pattern can find matches in web, but can't in Java?为什么该模式可以在网络中找到匹配项,而在 Java 中却不能? And sometimes I do matcher.find(); // return 2 matcher.group(1); // No match found exception有时我会做matcher.find(); // return 2 matcher.group(1); // No match found exception matcher.find(); // return 2 matcher.group(1); // No match found exception

This regex should work for you: [^\\\\](?:\\\\\\\\)*\\{(\\d+)(?:,(\\d*))?\\} .这个正则表达式应该对你[^\\\\](?:\\\\\\\\)*\\{(\\d+)(?:,(\\d*))?\\}[^\\\\](?:\\\\\\\\)*\\{(\\d+)(?:,(\\d*))?\\}

Part [^\\\\](?:\\\\\\\\)* addresses the case of slash escaping. [^\\\\](?:\\\\\\\\)*解决了斜线转义的情况。

Below is Java code example:下面是Java代码示例:

public static void main(String[] args) {
    Pattern p = Pattern.compile("[^\\\\](?:\\\\\\\\)*\\{(\\d+)(?:,(\\d*))?\\}");
    String testInput = "[a-z0-9]{1,2}|[a-z0-9]{3,}|[a-z0-9]{4}";
    Matcher matcher = p.matcher(testInput);
    while (matcher.find()){
        System.out.println("Next matching found:");
        if(matcher.group(2) == null){
            System.out.println("Strict: " + matcher.group(1));
        }else {
            System.out.println("Min: "
                    + matcher.group(1)
                    + ", Max: "
                    + ("".equals(matcher.group(2)) ? "Infinte" : matcher.group(2)));
        }
    }
}

Output:输出:

Next matching found:
Min: 1, Max: 2
Next matching found:
Min: 3, Max: Infinte
Next matching found:
Strict: 4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM