Java 如何检查给定的正则表达式是否有效?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2704857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:03:21  来源:igfitidea点击:

How to check if a given Regex is valid?

javaregex

提问by Philipp Andre

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

我有一个小程序,允许用户输入一些正则表达式。之后我想检查这个输入是否是一个有效的正则表达式。

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

我想知道 Java 中是否有内置方法,但找不到这样的 jet。

Can you give me some advice?

你能给我一些建议吗?

采纳答案by laz

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.

java RegexTester "(capture"然后输出"Unclosed group",例如。

回答by polygenelubricants

You can just Pattern.compilethe regex string and see if it throws PatternSyntaxException.

您可以只Pattern.compile使用正则表达式字符串,看看它是否throws PatternSyntaxException.

    String regex = "***";
    PatternSyntaxException exc = null;
    try {
        Pattern.compile(regex);
    } catch (PatternSyntaxException e) {
        exc = e;
    }
    if (exc != null) {
        exc.printStackTrace();
    } else {
        System.out.println("Regex ok!");
    }

This one in particular produces the following output:

这个特别产生以下输出:

java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
***
^


Regarding lookbehinds

关于后视

Here's a quote from the old trusty regular-expressions.info:

这是旧的可信赖的正则表达式.info的引用:

Important Notes About Lookbehind

Java takes things a step further by allowing finite repetition. You still cannot use the star or plus, but you can use the question mark and the curly braces with the max parameter specified. Java recognizes the fact that finite repetition can be rewritten as an alternation of strings with different, but fixed lengths.

关于 Lookbehind 的重要说明

Java 通过允许有限重复使事情更进一步。您仍然不能使用星号或加号,但您可以使用带有指定 max 参数的问号和花括号。Java 认识到有限重复可以重写为具有不同但固定长度的字符串的交替。

I think the phrase contains a typo, and should probably say "different, but finite lengths". In any case, Java does seem to allow alternation of different lengths in lookbehind.

我认为该短语包含一个错字,可能应该说“不同但有限的长度”。无论如何,Java 似乎确实允许在lookbehind 中交替使用不同的长度。

    System.out.println(
        java.util.Arrays.toString(
            "abracadabra".split("(?<=a|ab)")
        )
    ); // prints "[a, b, ra, ca, da, b, ra]"

There's also a bug in which you can actually have an infinite length lookbehind and have it work, but I wouldn't rely on such behaviors.

还有一个错误,您实际上可以在其中进行无限长度的后视并使其工作,但我不会依赖此类行为。

    System.out.println(
        "1234".replaceAll(".(?<=(^.*))", "!")
    ); // prints "1!12!123!1234!"

回答by ring bearer

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

最明显的事情是在 java.util.regex.Pattern 中使用 compile 方法并捕获 PatternSyntaxException

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

This will throw a PatternSyntaxExceptionif myRegEx is invalid.

PatternSyntaxException如果 myRegEx 无效,这将抛出一个。

回答by Sai Gopi N

 public class Solution
 {
 public static void main(String[] args){
  Scanner in = new Scanner(System.in);
  int testCases = Integer.parseInt(in.nextLine());
  while(testCases>0){
     String pattern = in.nextLine();
      try
      {
          Pattern.compile(pattern);
      }
      catch(Exception e)
      {
         // System.out.println(e.toString());
          System.out.println("Invalid");
      }
      System.out.println("Valid");
    }
 }
}

回答by Kirill Sidorov

public class Solution {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int testCases = Integer.parseInt(in.nextLine());
        while(testCases>0){
            String pattern = in.nextLine();
            try{
                Pattern.compile(pattern);
                System.out.println("Valid");
            }catch(PatternSyntaxException exception){
                System.out.println("Invalid");
            }

        }
    }
}

回答by Gurmeet Gulati

new String().matches(regEx) can be directly be used with try-catch to identify if regEx is valid.

new String().matches(regEx) 可以直接与 try-catch 一起使用来识别 regEx 是否有效。

boolean isValidRegEx = true;
try {
    new String().matches(regEx);
} catch(PatternSyntaxException e) {
    isValidRegEx = false;
}

回答by user3655403

try this :

尝试这个 :

import java.util.Scanner;
import java.util.regex.*;

public class Solution
{
      public static void main(String[] args){
      Scanner in = new Scanner(System.in);
      int testCases = Integer.parseInt(in.nextLine());
      while(testCases>0){
        String pattern = in.nextLine();
        if(pattern != null && !pattern.equals("")){
            try{
                Pattern.compile(pattern);
                System.out.println("Valid");
            }catch(PatternSyntaxException e){
                System.out.println("Invalid");
            }
        }
        testCases--;
        //Write your code
     }
  }
 }

use input to test :
3
([A-Z])(.+)
[AZa-z
batcatpat(nat

使用输入测试:
3
([AZ])(.+)
[AZa-z
batcatpat(nat