繁体   English   中英

将正则表达式匹配保存到数组中

[英]Saving regex matches into an array

我得到一个 url 字符串作为 Url class 的构造函数的输入,我想用我的正则表达式将它解析为协议、主机、端口、路径、查询等部分可能丢失的部分。 例如我可以得到https://domain:80/path或者我可以得到https://domain/path?query#fragment我需要一个 arrays 像这样:

["https", "://", "domain", ":80", "path", "", "", "", ""]

或者

["https", "://", "domain", "", "path", "?", "query", "#", "fragment"]

数组中的每个 substring 应该是使用匹配器的正则表达式中的一组。

稍后我将制作吸气剂,它会给我这个 url 的特定部分,或者我将简化路径,以防 /./ 或 /../ 在其中。 现在的问题是如何将它保存到一个数组中,以便以后可以使用。

也许,

 \\b(https?)(://)(?:w{3}\\.)?([^\\s/:]+)(:\\d{2,6})?/([^?/\\s]+)(\\?)?(\\w+)?#?(\\w+)?\\b

在某种程度上可能工作正常。

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){

        final String regex = "\\b(https?)(://)(?:w{3}\\.)?([^\\s/:]+)(:\\d{2,6})?/([^?/\\s]+)(\\?)?(\\w+)?#?(\\w+)?\\b";
        final String string = "https://domain:80/path or I could get https://domain/path?query#fragment https://www.domain:80/path or I could get http://domain/path?query#fragment ";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }

    }
}

Output

Full match: https://domain:80/path
Group 1: https
Group 2: ://
Group 3: domain
Group 4: :80
Group 5: path
Group 6: null
Group 7: null
Group 8: null
Full match: https://domain/path?query#fragment
Group 1: https
Group 2: ://
Group 3: domain
Group 4: null
Group 5: path
Group 6: ?
Group 7: query
Group 8: fragment
Full match: https://www.domain:80/path
Group 1: https
Group 2: ://
Group 3: domain
Group 4: :80
Group 5: path
Group 6: null
Group 7: null
Group 8: null
Full match: http://domain/path?query#fragment
Group 1: http
Group 2: ://
Group 3: domain
Group 4: null
Group 5: path
Group 6: ?
Group 7: query
Group 8: fragment

如果您想简化/修改/探索表达式,它已在regex101.com的右上角面板上进行了解释。 如果您愿意,您还可以在此链接中观看它如何与一些示例输入匹配。


正则表达式电路

jex.im可视化正则表达式:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM