用于验证 url、布尔值、字符串的 Java 正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7265941/
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-10-30 19:20:33  来源:igfitidea点击:

Java regex for validating url, boolean, string

javaregexvalidation

提问by Abhishek

I am in the process of formulating a regex for validating a text area that contains entries of the following format,

我正在制定一个正则表达式来验证包含以下格式条目的文本区域,

an url, boolean(true or false), string(with or without spaces)

An example is as follows,

一个例子如下,

http://www.yahoo.com, true, web mail site
http://www.google.com, false, a search site

So I was trying to formulate a regex for each line as below,

所以我试图为每一行制定一个正则表达式,如下所示,

(^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\+&%$#\=~])*$)(,(true|false))(,(.*))

Hence I can check each line, but this regex is not working. The whole regex fails to match the type of comma separated string. Also is there some way I can make this regex check for multiple lines and validating this pattern?

因此我可以检查每一行,但是这个正则表达式不起作用。整个正则表达式无法匹配逗号分隔字符串的类型。还有什么方法可以让这个正则表达式检查多行并验证这个模式?

回答by NullUserException

If the line breaks are your only problem, you could use the Pattern.MULTILINEflag:

如果换行符是您唯一的问题,您可以使用以下Pattern.MULTILINE标志:

Pattern.compile("^((?:https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]), (true|false), (.*)$", Pattern.MULTILINE|Pattern.CASE_INSENSITIVE);

You can also embed the flag(s):

您还可以嵌入标志

Pattern.compile("(?mi)^((?:https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]), (true|false), (.*)$",);

I took the liberty of using a different regex for your URL (it's from Regex Buddy). This also will put everything in a capture group.

我冒昧地为您的 URL 使用了不同的正则表达式(来自Regex Buddy)。这也将把所有东西都放在一个捕获组中。



Demo: http://ideone.com/I9vpB

演示:http: //ideone.com/I9vpB

public static void extract(String str) {

    Pattern regex = Pattern.compile("(?mi)^((?:https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|$!:,.;]*[A-Z0-9+&@#/%=~_|$]), (true|false), (.*)$");

    Matcher m = regex.matcher(str);
    while (m.find()) {
        System.out.println("URL:  " + m.group(1));
        System.out.println("Bool: " + m.group(2));
        System.out.println("Text: " + m.group(3) + "\n");
    }
}

public static void main (String[] args) throws java.lang.Exception
{
    String str = "http://www.yahoo.com, true, web mail site\nhttp://www.google.com, false, a search site";
    extract(str);
}

Outputs:

输出:

URL:  http://www.yahoo.com
Bool: true
Text: web mail site

URL:  http://www.google.com
Bool: false
Text: a search site