How to check if a given Regex is valid?

前端 未结 7 2243
时光取名叫无心
时光取名叫无心 2020-12-05 02:08

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 w

7条回答
  •  天涯浪人
    2020-12-05 02:27

    Most obvious thing to do would be using compile method in java.util.regex.Pattern and catch PatternSyntaxException

    String myRegEx;
    ...
    ...
    Pattern p = Pattern.compile(myRegEx);
    

    This will throw a PatternSyntaxException if myRegEx is invalid.

提交回复
热议问题