【问题标题】:Regular expression to match URLs in JavaJava中匹配URL的正则表达式
【发布时间】:2010-09-14 20:52:24
【问题描述】:

我在使用正则表达式时使用 RegexBuddy。我从它的库中复制了正则表达式以匹配 URL。我在 RegexBuddy 中成功测试。但是,当我将其复制为 Java String 风味并将其粘贴到 Java 代码中时,它不起作用。下面的类打印false

public class RegexFoo {

    public static void main(String[] args) {
        String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]";
        String text = "http://google.com";
        System.out.println(IsMatch(text,regex));
}

    private static boolean IsMatch(String s, String pattern) {
        try {
            Pattern patt = Pattern.compile(pattern);
            Matcher matcher = patt.matcher(s);
            return matcher.matches();
        } catch (RuntimeException e) {
        return false;
    }       
}   
}

有谁知道我做错了什么?

【问题讨论】:

  • 塞尔吉奥,不要捕获 RuntimeException。它可能会引入细微的错误,并且总体上是一种不好的做法。如果您只想忽略表达式非法时的场景,请使用:} catch ( PatternSyntaxException pse ){} 代替。见第 57 项:java.sun.com/docs/books/effective
  • 或者你可以使用 Pattern patt = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);避免更改正则表达式以匹配大小写。
  • 我知道这真的很旧('08),但对于任何有类似问题的人,RegexBuddy 都有“使用”选项卡。确保您首先选择 Java 7 风格,然后在“使用”面板中,您可以让它为您的特定情况生成 Java 代码。这对我来说效果很好。

标签: java regex regexbuddy


【解决方案1】:

首先,一个正则表达式示例:

regex = “((http|https)://)(www.)?” 
+ “[a-zA-Z0-9@:%._\\+~#?&//=]{2,256}\\.[a-z]” 
+ “{2,6}\\b([-a-zA-Z0-9@:%._\\+~#?&//=]*)”

*URL 必须以 http 或 https 开头,并且 * 然后是 :// 和 *那么它必须包含www。和 *然后是长度为 (2, 256) 的子域和 *最后一部分包含顶级域名,如 .com、.org 等。


在 JAVA 中

// Java program to check URL is valid or not
// using Regular Expression
 
import java.util.regex.*;
 
class GFG {
 
    // Function to validate URL
    // using regular expression
    public static boolean
    isValidURL(String url)
    {
        // Regex to check valid URL
        String regex = "((http|https)://)(www.)?"
              + "[a-zA-Z0-9@:%._\\+~#?&//=]"
              + "{2,256}\\.[a-z]"
              + "{2,6}\\b([-a-zA-Z0-9@:%"
              + "._\\+~#?&//=]*)";
 
        // Compile the ReGex
        Pattern p = Pattern.compile(regex);
 
        // If the string is empty
        // return false
        if (url == null) {
            return false;
        }
 
        // Find match between given string
        // and regular expression
        // using Pattern.matcher()
        Matcher m = p.matcher(url);
 
        // Return if the string
        // matched the ReGex
        return m.matches();
    }
 
    // Driver code
    public static void main(String args[])
    {
        String url
            = "https://www.superDev.org";
        if (isValidURL(url) == true) {
            System.out.println("Yes");
        }
        else
            System.out.println("NO");
    }
}

在 python 3 中

# Python3 program to check
# URL is valid or not
# using regular expression
import re
 
# Function to validate URL
# using regular expression
def isValidURL(str):
 
    # Regex to check valid URL
    regex = ("((http|https)://)(www.)?" +
             "[a-zA-Z0-9@:%._\\+~#?&//=]" +
             "{2,256}\\.[a-z]" +
             "{2,6}\\b([-a-zA-Z0-9@:%" +
             "._\\+~#?&//=]*)")
     
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if (str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
# Driver code
 
# Test Case 1:
url = "https://www.superDev.org"
 
if(isValidURL(url) == True):
    print("Yes")
else:
    print("No")
 

【讨论】:

    【解决方案2】:

    这是一个 URL 解析器正则表达式的提议,它可以识别:

    • 协议
    • 主机
    • 端口
    • 路径(文档/文件夹)
    • 获取参数
    ^(?>(?<protocol>[[:alpha:]]+(?>\:[[:alpha:]]+)*)\:\/\/)?(?<host>(?>[[:alnum:]]|[-_.])+)(?>\:(?<port>[[:digit:]]+))?(?<path>\/(?>[[:alnum:]]|[-_.\/])*)?(?>\?(?<request>(?>[[:alnum:]]+=[[:alnum:]]+)(?>\&(?>[[:alnum:]]+=[[:alnum:]]+))*))?$
    

    这个正则表达式能够解析这样的 URL:

    jdbc:hsqldb:hsql://localhost:91/index.
    

    有很多方法可以设计 URL 正则表达式,因此我建议的方法可以稍微调整以匹配更准确的 URL 语法。

    可以在以下页面进行测试:https://regex101.com/r/Dy7HE0/5

    请注意,用于正则表达式的语言原生 API(例如 java.util.regex)不支持智能字符类,例如 [[:alnum:]][[:阿尔法:]]

    改用 \w\d

    【讨论】:

      【解决方案3】:
      ((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\.[a-zA-Z]+
      

      在这里查看:- https://www.freeformatter.com/java-regex-tester.html#ad-output

      正确地整理出这些条目

      【讨论】:

      • 特殊字符失败
      • 我需要正则表达式来从歌曲名称中删除 url。找不到一个,或者我应该说大多数都失败了,所以我发布了对我有用的方法:)
      • 是的。在提供的链接上检查它。
      【解决方案4】:

      根据 billjamesdev 的回答,这是另一种不使用 RegEx 验证 URL 的方法:

      Apache Commons Validator lib,查看类UrlValidator。一些示例代码:

      使用“http”和“https”的有效方案构造一个 UrlValidator。

      String[] schemes = {"http","https"}.
      UrlValidator urlValidator = new UrlValidator(schemes);
      if (urlValidator.isValid("ftp://foo.bar.com/")) {
         System.out.println("url is valid");
      } else {
         System.out.println("url is invalid");
      }
      
      prints "url is invalid"
      

      如果改为使用默认构造函数。

      UrlValidator urlValidator = new UrlValidator();
      if (urlValidator.isValid("ftp://foo.bar.com/")) {
         System.out.println("url is valid");
      } else {
         System.out.println("url is invalid");
      }
      

      打印出“url有效”

      【讨论】:

        【解决方案5】:

        我会尝试一个标准的“你为什么这样做?”回答...你知道java.net.URL吗?

        URL url = new URL(stringURL);
        

        如果无法解析 URL,上面将抛出 MalformedURLException

        【讨论】:

        • 我要走正则表达式的路。我在这里发布的内容尽可能简单,以使我的问题清楚。在我的程序中,我在更复杂的正则表达式中使用 URL 正则表达式。
        • 这很酷。我没有更好的正则表达式答案,所以我想我会发布一个替代方案。不过,没想到我会因此而被贬低。
        • 你是对的,也许下勾有点多。 “我会试试这个标准”听起来有点冒犯。
        • 酷(抱歉,快放假了)。是的,绝对不是这样的。我只是在这里看到了很多,有时甚至会有所帮助。
        • "new URL" 仅在端口 1.2.3.1.2.3.4.51.2,3.4.5:等
        【解决方案6】:

        现在最好的方法是:

        android.util.Patterns.WEB_URL.matcher(linkUrl).matches();
        

        编辑:Patterns 的代码来自https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Patterns.java

        /*
         * Copyright (C) 2007 The Android Open Source Project
         *
         * Licensed under the Apache License, Version 2.0 (the "License");
         * you may not use this file except in compliance with the License.
         * You may obtain a copy of the License at
         *
         *      http://www.apache.org/licenses/LICENSE-2.0
         *
         * Unless required by applicable law or agreed to in writing, software
         * distributed under the License is distributed on an "AS IS" BASIS,
         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
         * See the License for the specific language governing permissions and
         * limitations under the License.
         */
        
        package android.util;
        
        import java.util.regex.Matcher;
        import java.util.regex.Pattern;
        
        /**
         * Commonly used regular expression patterns.
         */
        public class Patterns {
            /**
             *  Regular expression to match all IANA top-level domains.
             *  List accurate as of 2011/07/18.  List taken from:
             *  http://data.iana.org/TLD/tlds-alpha-by-domain.txt
             *  This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py
             *
             *  @deprecated Due to the recent profileration of gTLDs, this API is
             *  expected to become out-of-date very quickly. Therefore it is now
             *  deprecated.
             */
            @Deprecated
            public static final String TOP_LEVEL_DOMAIN_STR =
                "((aero|arpa|asia|a[cdefgilmnoqrstuwxz])"
                + "|(biz|b[abdefghijmnorstvwyz])"
                + "|(cat|com|coop|c[acdfghiklmnoruvxyz])"
                + "|d[ejkmoz]"
                + "|(edu|e[cegrstu])"
                + "|f[ijkmor]"
                + "|(gov|g[abdefghilmnpqrstuwy])"
                + "|h[kmnrtu]"
                + "|(info|int|i[delmnoqrst])"
                + "|(jobs|j[emop])"
                + "|k[eghimnprwyz]"
                + "|l[abcikrstuvy]"
                + "|(mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])"
                + "|(name|net|n[acefgilopruz])"
                + "|(org|om)"
                + "|(pro|p[aefghklmnrstwy])"
                + "|qa"
                + "|r[eosuw]"
                + "|s[abcdeghijklmnortuvyz]"
                + "|(tel|travel|t[cdfghjklmnoprtvwz])"
                + "|u[agksyz]"
                + "|v[aceginu]"
                + "|w[fs]"
                + "|(\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae|\u0438\u0441\u043f\u044b\u0442\u0430\u043d\u0438\u0435|\u0440\u0444|\u0441\u0440\u0431|\u05d8\u05e2\u05e1\u05d8|\u0622\u0632\u0645\u0627\u06cc\u0634\u06cc|\u0625\u062e\u062a\u0628\u0627\u0631|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633|\u0633\u0648\u0631\u064a\u0629|\u0641\u0644\u0633\u0637\u064a\u0646|\u0642\u0637\u0631|\u0645\u0635\u0631|\u092a\u0930\u0940\u0915\u094d\u0937\u093e|\u092d\u093e\u0930\u0924|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd|\u0baa\u0bb0\u0bbf\u0b9f\u0bcd\u0b9a\u0bc8|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e44\u0e17\u0e22|\u30c6\u30b9\u30c8|\u4e2d\u56fd|\u4e2d\u570b|\u53f0\u6e7e|\u53f0\u7063|\u65b0\u52a0\u5761|\u6d4b\u8bd5|\u6e2c\u8a66|\u9999\u6e2f|\ud14c\uc2a4\ud2b8|\ud55c\uad6d|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)"
                + "|y[et]"
                + "|z[amw])";
        
            /**
             *  Regular expression pattern to match all IANA top-level domains.
             *  @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.
             */
            @Deprecated
            public static final Pattern TOP_LEVEL_DOMAIN =
                Pattern.compile(TOP_LEVEL_DOMAIN_STR);
        
            /**
             *  Regular expression to match all IANA top-level domains for WEB_URL.
             *  List accurate as of 2011/07/18.  List taken from:
             *  http://data.iana.org/TLD/tlds-alpha-by-domain.txt
             *  This pattern is auto-generated by frameworks/ex/common/tools/make-iana-tld-pattern.py
             *
             *  @deprecated This API is deprecated. See {@link #TOP_LEVEL_DOMAIN_STR}.
             */
            @Deprecated
            public static final String TOP_LEVEL_DOMAIN_STR_FOR_WEB_URL =
                "(?:"
                + "(?:aero|arpa|asia|a[cdefgilmnoqrstuwxz])"
                + "|(?:biz|b[abdefghijmnorstvwyz])"
                + "|(?:cat|com|coop|c[acdfghiklmnoruvxyz])"
                + "|d[ejkmoz]"
                + "|(?:edu|e[cegrstu])"
                + "|f[ijkmor]"
                + "|(?:gov|g[abdefghilmnpqrstuwy])"
                + "|h[kmnrtu]"
                + "|(?:info|int|i[delmnoqrst])"
                + "|(?:jobs|j[emop])"
                + "|k[eghimnprwyz]"
                + "|l[abcikrstuvy]"
                + "|(?:mil|mobi|museum|m[acdeghklmnopqrstuvwxyz])"
                + "|(?:name|net|n[acefgilopruz])"
                + "|(?:org|om)"
                + "|(?:pro|p[aefghklmnrstwy])"
                + "|qa"
                + "|r[eosuw]"
                + "|s[abcdeghijklmnortuvyz]"
                + "|(?:tel|travel|t[cdfghjklmnoprtvwz])"
                + "|u[agksyz]"
                + "|v[aceginu]"
                + "|w[fs]"
                + "|(?:\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae|\u0438\u0441\u043f\u044b\u0442\u0430\u043d\u0438\u0435|\u0440\u0444|\u0441\u0440\u0431|\u05d8\u05e2\u05e1\u05d8|\u0622\u0632\u0645\u0627\u06cc\u0634\u06cc|\u0625\u062e\u062a\u0628\u0627\u0631|\u0627\u0644\u0627\u0631\u062f\u0646|\u0627\u0644\u062c\u0632\u0627\u0626\u0631|\u0627\u0644\u0633\u0639\u0648\u062f\u064a\u0629|\u0627\u0644\u0645\u063a\u0631\u0628|\u0627\u0645\u0627\u0631\u0627\u062a|\u0628\u06be\u0627\u0631\u062a|\u062a\u0648\u0646\u0633|\u0633\u0648\u0631\u064a\u0629|\u0641\u0644\u0633\u0637\u064a\u0646|\u0642\u0637\u0631|\u0645\u0635\u0631|\u092a\u0930\u0940\u0915\u094d\u0937\u093e|\u092d\u093e\u0930\u0924|\u09ad\u09be\u09b0\u09a4|\u0a2d\u0a3e\u0a30\u0a24|\u0aad\u0abe\u0ab0\u0aa4|\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe|\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8|\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa\u0bc2\u0bb0\u0bcd|\u0baa\u0bb0\u0bbf\u0b9f\u0bcd\u0b9a\u0bc8|\u0c2d\u0c3e\u0c30\u0c24\u0c4d|\u0dbd\u0d82\u0d9a\u0dcf|\u0e44\u0e17\u0e22|\u30c6\u30b9\u30c8|\u4e2d\u56fd|\u4e2d\u570b|\u53f0\u6e7e|\u53f0\u7063|\u65b0\u52a0\u5761|\u6d4b\u8bd5|\u6e2c\u8a66|\u9999\u6e2f|\ud14c\uc2a4\ud2b8|\ud55c\uad6d|xn\\-\\-0zwm56d|xn\\-\\-11b5bs3a9aj6g|xn\\-\\-3e0b707e|xn\\-\\-45brj9c|xn\\-\\-80akhbyknj4f|xn\\-\\-90a3ac|xn\\-\\-9t4b11yi5a|xn\\-\\-clchc0ea0b2g2a9gcd|xn\\-\\-deba0ad|xn\\-\\-fiqs8s|xn\\-\\-fiqz9s|xn\\-\\-fpcrj9c3d|xn\\-\\-fzc2c9e2c|xn\\-\\-g6w251d|xn\\-\\-gecrj9c|xn\\-\\-h2brj9c|xn\\-\\-hgbk6aj7f53bba|xn\\-\\-hlcj6aya9esc7a|xn\\-\\-j6w193g|xn\\-\\-jxalpdlp|xn\\-\\-kgbechtv|xn\\-\\-kprw13d|xn\\-\\-kpry57d|xn\\-\\-lgbbat1ad8j|xn\\-\\-mgbaam7a8h|xn\\-\\-mgbayh7gpa|xn\\-\\-mgbbh1a71e|xn\\-\\-mgbc0a9azcg|xn\\-\\-mgberp4a5d4ar|xn\\-\\-o3cw4h|xn\\-\\-ogbpf8fl|xn\\-\\-p1ai|xn\\-\\-pgbs0dh|xn\\-\\-s9brj9c|xn\\-\\-wgbh1c|xn\\-\\-wgbl6a|xn\\-\\-xkc2al3hye2a|xn\\-\\-xkc2dl3a5ee0h|xn\\-\\-yfro4i67o|xn\\-\\-ygbi2ammx|xn\\-\\-zckzah|xxx)"
                + "|y[et]"
                + "|z[amw]))";
        
            /**
             * Good characters for Internationalized Resource Identifiers (IRI).
             * This comprises most common used Unicode characters allowed in IRI
             * as detailed in RFC 3987.
             * Specifically, those two byte Unicode characters are not included.
             */
            public static final String GOOD_IRI_CHAR =
                "a-zA-Z0-9\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";
        
            public static final Pattern IP_ADDRESS
                = Pattern.compile(
                    "((25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9])\\.(25[0-5]|2[0-4]"
                    + "[0-9]|[0-1][0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]"
                    + "[0-9]{2}|[1-9][0-9]|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}"
                    + "|[1-9][0-9]|[0-9]))");
        
            /**
             * RFC 1035 Section 2.3.4 limits the labels to a maximum 63 octets.
             */
            private static final String IRI
                = "[" + GOOD_IRI_CHAR + "]([" + GOOD_IRI_CHAR + "\\-]{0,61}[" + GOOD_IRI_CHAR + "]){0,1}";
        
            private static final String GOOD_GTLD_CHAR =
                "a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF";
            private static final String GTLD = "[" + GOOD_GTLD_CHAR + "]{2,63}";
            private static final String HOST_NAME = "(" + IRI + "\\.)+" + GTLD;
        
            public static final Pattern DOMAIN_NAME
                = Pattern.compile("(" + HOST_NAME + "|" + IP_ADDRESS + ")");
        
            /**
             *  Regular expression pattern to match most part of RFC 3987
             *  Internationalized URLs, aka IRIs.  Commonly used Unicode characters are
             *  added.
             */
            public static final Pattern WEB_URL = Pattern.compile(
                "((?:(http|https|Http|Https|rtsp|Rtsp):\\/\\/(?:(?:[a-zA-Z0-9\\$\\-\\_\\.\\+\\!\\*\\'\\(\\)"
                + "\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,64}(?:\\:(?:[a-zA-Z0-9\\$\\-\\_"
                + "\\.\\+\\!\\*\\'\\(\\)\\,\\;\\?\\&\\=]|(?:\\%[a-fA-F0-9]{2})){1,25})?\\@)?)?"
                + "(?:" + DOMAIN_NAME + ")"
                + "(?:\\:\\d{1,5})?)" // plus option port number
                + "(\\/(?:(?:[" + GOOD_IRI_CHAR + "\\;\\/\\?\\:\\@\\&\\=\\#\\~"  // plus option query params
                + "\\-\\.\\+\\!\\*\\'\\(\\)\\,\\_])|(?:\\%[a-fA-F0-9]{2}))*)?"
                + "(?:\\b|$)"); // and finally, a word boundary or end of
                                // input.  This is to stop foo.sure from
                                // matching as foo.su
        
            public static final Pattern EMAIL_ADDRESS
                = Pattern.compile(
                    "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
                    "\\@" +
                    "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
                    "(" +
                        "\\." +
                        "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
                    ")+"
                );
        
            /**
             * This pattern is intended for searching for things that look like they
             * might be phone numbers in arbitrary text, not for validating whether
             * something is in fact a phone number.  It will miss many things that
             * are legitimate phone numbers.
             *
             * <p> The pattern matches the following:
             * <ul>
             * <li>Optionally, a + sign followed immediately by one or more digits. Spaces, dots, or dashes
             * may follow.
             * <li>Optionally, sets of digits in parentheses, separated by spaces, dots, or dashes.
             * <li>A string starting and ending with a digit, containing digits, spaces, dots, and/or dashes.
             * </ul>
             */
            public static final Pattern PHONE
                = Pattern.compile(                      // sdd = space, dot, or dash
                        "(\\+[0-9]+[\\- \\.]*)?"        // +<digits><sdd>*
                        + "(\\([0-9]+\\)[\\- \\.]*)?"   // (<digits>)<sdd>*
                        + "([0-9][0-9\\- \\.]+[0-9])"); // <digit><digit|sdd>+<digit>
        
            /**
             *  Convenience method to take all of the non-null matching groups in a
             *  regex Matcher and return them as a concatenated string.
             *
             *  @param matcher      The Matcher object from which grouped text will
             *                      be extracted
             *
             *  @return             A String comprising all of the non-null matched
             *                      groups concatenated together
             */
            public static final String concatGroups(Matcher matcher) {
                StringBuilder b = new StringBuilder();
                final int numGroups = matcher.groupCount();
        
                for (int i = 1; i <= numGroups; i++) {
                    String s = matcher.group(i);
        
                    if (s != null) {
                        b.append(s);
                    }
                }
        
                return b.toString();
            }
        
            /**
             * Convenience method to return only the digits and plus signs
             * in the matching string.
             *
             * @param matcher      The Matcher object from which digits and plus will
             *                     be extracted
             *
             * @return             A String comprising all of the digits and plus in
             *                     the match
             */
            public static final String digitsAndPlusOnly(Matcher matcher) {
                StringBuilder buffer = new StringBuilder();
                String matchingRegion = matcher.group();
        
                for (int i = 0, size = matchingRegion.length(); i < size; i++) {
                    char character = matchingRegion.charAt(i);
        
                    if (character == '+' || Character.isDigit(character)) {
                        buffer.append(character);
                    }
                }
                return buffer.toString();
            }
        
            /**
             * Do not create this static utility class.
             */
            private Patterns() {}
        }
        

        【讨论】:

        • +1 为您服务!太感谢了!!!这是很棒的代码!每个人都在尝试使用困难的正则表达式,而这可能很容易。太棒了!
        • @JPM 除了 OP 正在寻找 Java 解决方案而不是 Android 特定解决方案(容易忘记查看 Q 的特定标签)。不过,对于那些为 Android 编写代码的人来说,这是一件好事,所以我提高了。
        • @indivisible 幸运的是,Android 是开源的,你可以从github.com/android/platform_frameworks_base/blob/master/core/… 获取代码:)
        • @EpicPandaForce 我认为您的评论是使这个答案可以接受/有帮助的唯一原因,因为问题是寻找java 解决方案,而不是android
        • 它不检查 url 是从 http 还是从 https 开始的。我用 www.www 测试过,它给了我真实的信息。所以对我没用
        【解决方案7】:

        改用以下正则表达式字符串。您的测试可能是以区分大小写的方式完成的。我添加了小写字母以及正确的字符串开头占位符。

        String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        

        这也有效:

        String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
        

        注意:

        String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>
        
        String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>
        

        【讨论】:

        • 使用你的正则表达式我也得到了错误。
        • 你看到我最后的编辑了吗?我用手指抚摸着弦的开头。我刚刚将它复制到 Eclipse 中,我得到了“真实”。
        • 谢谢,我第一次看到 stackoverflow 中 cmets 的实用程序
        • 没问题。如果您使用的是 Eclipse,我喜欢使用此处提供的 RegEx Tester 插件brosinski.com/regex
        • 感谢我正在使用 eclipse 的链接
        【解决方案8】:

        所有建议方法的问题:所有 RegEx 都在验证

        所有基于 RegEx 的代码都被过度设计:它只会找到有效的 URL!作为示例,它将忽略以“http://”开头且内部包含非 ASCII 字符的任何内容。

        甚至更多:我遇到过使用 Java RegEx 包(从文本中过滤电子邮件地址)的 1-2 秒处理时间(单线程、专用),用于处理非常小而简单的句子,没有什么特别的; Java 6 RegEx 中可能存在错误...

        最简单/最快的解决方案是使用 StringTokenizer 将文本拆分为标记,删除以“http://”等开头的标记,并再次将标记连接成文本。

        如果你想从文本中过滤电子邮件(因为稍后你会做 NLP 人员等) - 只需删除所有包含“@”的标记。

        这是 Java 6 的 RegEx 失败的简单文本。在 Java 的不同变体中尝试一下。在长时间运行的单线程测试应用程序中,每次 RegEx 调用大约需要 1000 毫秒:

        pattern = Pattern.compile("[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})", Pattern.CASE_INSENSITIVE);
        
        "Avalanna is such a sweet little girl! It would b heartbreaking if cancer won. She's so precious! #BeliebersPrayForAvalanna");
        "@AndySamuels31 Hahahahahahahahahhaha lol, you don't look like a girl hahahahhaahaha, you are... sexy.";
        

        如果您只需要过滤带有“@”、“http://”、“ftp://”、“mailto:”的单词,请不要依赖正则表达式;这是巨大的工程开销。

        如果你真的想在 Java 中使用 RegEx,试试Automaton

        【讨论】:

        • 大声笑。 Automaton 不支持捕获组。
        • 我不明白你的担心。接受的答案的正则表达式实际上可以很好地验证 URL。你似乎在嘲笑它,说it will find only valid URLs!——这就是OP问题的目标。我错过了什么吗?
        【解决方案9】:

        使用 RegexBuddy 库中的正则表达式时,请确保在您自己的代码中使用与库中的正则表达式相同的匹配模式。如果在Use选项卡上生成源代码sn-p,RegexBuddy会自动在源代码sn-p中设置正确的匹配选项。如果您复制/粘贴正则表达式,则必须自己进行。

        在这种情况下,正如其他人指出的那样,您错过了不区分大小写选项。

        【讨论】:

          【解决方案10】:

          这也有效:

          String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
          

          注意:

          String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>
          
          String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>
          

          所以可能第一个对于一般用途更有用。

          【讨论】:

            猜你喜欢
            • 2012-02-04
            • 2013-03-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多