【问题标题】:Saving regex matches into an array将正则表达式匹配保存到数组中
【发布时间】:2020-02-17 00:47:18
【问题描述】:

我得到一个 url 字符串作为 Url 类的构造函数的输入,我想用我的正则表达式将它解析为 protocol、host、port、path、query、fragmet 等部分,其中某些部分可以失踪。例如我可以得到https://domain:80/path 或者我可以得到https://domain/path?query#fragment 我需要这样的数组:

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

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

数组中的每个子字符串都应该是使用匹配器的正则表达式中的一组。

稍后我将制作 getter,它将为我提供此 url 的特定部分,或者我将简化路径,以防 /./ 或 /../ 在其中。 现在的问题是如何将其保存到一个数组中,以便以后使用。

【问题讨论】:

  • 你为什么不把它分配给一个 URL 类,然后使用内置方法来实现你想要的?
  • 因为我有点不能使用内置函数:D
  • 您是说您可以使用regex 解析器的内置功能(即方法),但不允许使用专门为此目的创建的类的方法?这真的没有多大意义。是什么迫使你受到这种限制?
  • 是的,这对我来说也没有意义,但这是一个不允许的练习,我应该这样做。
  • 然后您需要查看PatternMatcher 类,然后在URL 或其他内容上尝试一些示例。如果您遇到问题,请尝试修改您的问题,有人会帮助您。

标签: java arrays regex url save


【解决方案1】:

也许,

\\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));
            }
        }

    }
}

输出

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 的右上角面板中已对此进行了说明。如果您愿意,您还可以在this link 中观看它如何与一些示例输入匹配。


正则表达式电路

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-25
    • 2014-02-06
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    相关资源
    最近更新 更多