iOS - 网址、链接、网页地址、下载链接等正则表达式匹配(解决url包含中文不能编码的问题)

 

DNS规定,域名中的标号都由英文字母和数字组成,每一个标号不超过63个字符,也不区分大小写字母。标号中除连字符(-)外不能使用其他的标点符号。级别最低的域名写在最左边,而级别最高的域名写在最右边。由多个标号组成的完整域名总共不超过255个字符。

由此匹配完整域名的正则表达式:

  

 ^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$

 

例如:baidu.com 

 

 匹配网址:

^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*$

 

例如: http://www.baidu.com

 

匹配http url:

^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*([\?&]\w+=\w*)*$

 

例如: http://www.tetet.com/index.html?q=1&m=test

 

 

 

项目中WKWebView使用:

 

WKWebView *_detailWebView;

 

//识别二维码跳转;不是链接显示内容点击网址跳转

    if ([self.m_url hasPrefix:@"http"]) {

//        NSString *urlStr = [self.m_url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

        // 解决url包含中文不能编码的问题

        NSString *urlStr = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)self.m_url,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));

        NSURL *url = [NSURL URLWithString:urlStr];

        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];

        [request setHTTPShouldHandleCookies:YES];

        [_detailWebView loadRequest:request];

 

    } else {

        self.topTitleLabel.text = @"扫描结果";

        

        QRCodeLabel = [[ZXLabel alloc]initWithFrame:CGRectMake(10, 10, SCREENWIDTH-20, 50) fontSize:16 text:@"" textColor:[UIColor colorWithHexString:@"#000000"] textAlignment:NSTextAlignmentLeft numberOfLines:0];

        [_detailWebView addSubview:QRCodeLabel];

 

        if ([self urlValidation:[NSString stringWithFormat:@"%@",self.m_url]]==YES) {//网址

            [self textColour];

            QRurlStr = [NSString stringWithFormat:@"http://%@",[NSString stringWithFormat:@"%@",self.m_url]];

        } else {

            // 文字html可拷贝,查询

            QRurlStr = [NSString stringWithFormat:@"<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><meta name='viewport' content='width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no'><style>*{margin:5px;padding:0px;}</style><title></title></head<body>%@</body></html>",[NSString stringWithFormat:@"%@",self.m_url]];

            [_detailWebView loadHTMLString:QRurlStr  baseURL:Nil];

        }

    }

 

 

 

#pragma mark -- 识别图中二维码

/**

 *  网址正则验证

 *

 *  @param string 要验证的字符串

 *

 *  @return 返回值类型为BOOL

 */

- (BOOL)urlValidation:(NSString *)string {

    NSError *error;

    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$";

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error];

    NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];

    for (NSTextCheckingResult *match in arrayOfAllMatches){

        NSString* substringForMatch = [string substringWithRange:match.range];

        NSLog(@"匹配--%@",substringForMatch);

        return YES;

    }

    return NO;

}

 

- (void)textColour {

    NSMutableAttributedString *abs = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",self.m_url]];

    [abs beginEditing];

    //字体大小

    //        [abs addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0] range:NSMakeRange(0, 2)];

    //字体颜色

    [abs addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor]  range:NSMakeRange(0,[NSString stringWithFormat:@"%@",self.m_url].length)];

    //下划线

    [abs addAttribute:NSUnderlineStyleAttributeName  value:@(NSUnderlineStyleSingle) range:NSMakeRange(0,[NSString stringWithFormat:@"%@",self.m_url].length)];

    QRCodeLabel.attributedText = abs;

    UITapGestureRecognizer *LabelTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(capchaBtn:)];

    QRCodeLabel.userInteractionEnabled = YES;

    [QRCodeLabel addGestureRecognizer:LabelTap];

}

 

// 链接跳转

- (void)capchaBtn:(UITapGestureRecognizer *)sendr{

    NSLog(@"跳转网页~~");

    [QRCodeLabel removeFromSuperview];

    //NSString *urlStr = [QRurlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *urlStr = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)QRurlStr,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL,kCFStringEncodingUTF8));

    NSURL *url =[NSURL URLWithString:urlStr];

    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];

    [request setHTTPShouldHandleCookies:YES];

    [_detailWebView loadRequest:request];

}

 

posted @ 2018-04-10 11:29  公羽寒  阅读(1385)  评论(0编辑  收藏  举报