zoukankan      html  css  js  c++  java
  • IOS 正则表达式匹配文本中URL位置并获取URL所在位置(解决连接中文问题)

    需求很简单,是从一段文本中匹配出其中的超链接。基本的做法就是用正则表达式去匹配。但是有这样一个问题。

    网上大部分的识别URL的正则表达式url末尾有空格的情况下可以正确识别。比如这样的情况。

    我是一段中文https://github.com/TinyQ 我还是一段中文

    但是如果去掉TinyQ 后面的空格。匹配到的将是 “https://github.com/TinyQ我还是一段中文” 是连上的。

    最后替换过好多正则才得以解决。这里贴上代码:

    NSError *error;
        NSString *regulaStr = @"\bhttps?://[a-zA-Z0-9\-.]+(?::(\d+))?(?:(?:/[a-zA-Z0-9\-._?,'+\&%$=~*!():@\\]*)+)?";
        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");
    }

    这里做个更新。下面这个正则也是可以的。而且应该更好一些。

    比如这种 Explorerwww.chiphell.com/ 。 也是可以识别出 www.chjiphell.com

    ((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\.\-~!@#$%^&*+?:_/=<>]*)?)

  • 相关阅读:
    C++中的类模板详细讲述
    IE6
    Active Driectory 操作(转来放起来,不要丢了)
    The length of the query string for this request exceeds the configured maxQueryStringLength value
    试一下用word发布一篇文章
    各种分享api
    汇编语言程序设计 检测点1.1
    Windows下配置使用MemCached
    chrome
    ASP.NET 把集合导出为Excel的一个助手类
  • 原文地址:https://www.cnblogs.com/CCSSPP/p/3337947.html
Copyright © 2011-2022 走看看