如何检查给定的正则表达式是否有效? [英] 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.
我想知道Java中是否有内置方法,但是找不到这种喷射器.
I'm wondering if there is a build-in method in Java, but could not find such jet.
你能给我一些建议吗?
推荐答案
这里是一个示例.
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"
然后输出"Unclosed group"
.
这篇关于如何检查给定的正则表达式是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文