1

I have pattern [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"

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. 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? And sometimes I do matcher.find(); // return 2 matcher.group(1); // No match found exception

0

1 Answer 1

1

This regex should work for you: [^\\](?:\\\\)*\{(\d+)(?:,(\d*))?\}.

Part [^\\](?:\\\\)* addresses the case of slash escaping.

Below is Java code example:

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your trying, but both variant was unsuccessful. Yes, I checked them by the link you provided, but in Java it doesn't work((( And, by the way, what is mean ?: Is it greedy quantifier? If I choose ? -it is mean 0/1 times, but what is about ?:
Check update... Construction like (?:) meas non-capturing group, i.e. the group that you wouldn't like to parse but rather for use just as a part of your rule.
Why need that part [^\\\\](?:\\\\\\\\) ?
because your expression might have slashes as the escape symbols. Since slash can be used to escape slashes, this part is used in order to check if \{ is escaped { or it is a part of bigger picture like \\{ where { defines the quantifier of `\` literal.
I would never thought about that :) and even after your explanation, I hardly understand that) but thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.