Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

java - How to check if a given Regex is valid?

I have a little program allowing users to type-in some regular expressions. afterwards I like to check if this input is a valid regex or not.

I'm wondering if there is a build-in method in Java, but could not find such jet.

Can you give me some advice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is an example.

import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class RegexTester {
    public static void main(String[] arguments) {
        String userInputPattern = arguments[0];
        try {
            Pattern.compile(userInputPattern);
        } catch (PatternSyntaxException exception) {
            System.err.println(exception.getDescription());
            System.exit(1);
        }
        System.out.println("Syntax is ok.");
    }
}

java RegexTester "(capture" then outputs "Unclosed group", for example.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...