如何在 Swift 中使用正则表达式? [英] How to use regex with Swift?

查看:46
本文介绍了如何在 Swift 中使用正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Swift 中制作一个应用程序,我需要从字符串中捕获 8 个数字.这是字符串:index.php?page=index&l=99182677

I am making an app in Swift and I need to catch 8 numbers from a string. Here's the string: index.php?page=index&l=99182677

我的模式是:&l=(\d{8,})

这是我的代码:

var yourAccountNumber = "index.php?page=index&l=99182677"
let regex = try! NSRegularExpression(pattern: "&l=(\\d{8,})", options: NSRegularExpressionOptions.CaseInsensitive)
let range = NSMakeRange(0, yourAccountNumber.characters.count)
let match = regex.matchesInString(yourAccountNumber, options: NSMatchingOptions.Anchored, range: range)

首先,我不知道 NSMatchingOptions 是什么意思,在 苹果官方库,我没有得到所有的 .Anchored、.ReportProgress 等内容.任何人都可以让我轻松一下吗?

Firstly, I don't know what the NSMatchingOptions means, on the official Apple library, I don't get all the .Anchored, .ReportProgress, etc stuff. Anyone would be able to lighten me up on this?

然后,当我 print(match) 时,该变量 ([]) 中似乎没有任何内容.

Then, when I print(match), nothing seems to contain on that variable ([]).

我使用 Xcode 7 Beta 3 和 Swift 2.0.

I am using Xcode 7 Beta 3, with Swift 2.0.

推荐答案

ORIGINAL ANSWER

您可以利用以下函数来获取捕获的组文本:

ORIGINAL ANSWER

Here is a function you can leverage to get captured group texts:

import Foundation

extension String {
    func firstMatchIn(string: NSString!, atRangeIndex: Int!) -> String {
        var error : NSError?
        let re = NSRegularExpression(pattern: self, options: .CaseInsensitive, error: &error)
        let match = re.firstMatchInString(string, options: .WithoutAnchoringBounds, range: NSMakeRange(0, string.length))
        return string.substringWithRange(match.rangeAtIndex(atRangeIndex))
    }
}

然后:

var result = "&l=(\\d{8,})".firstMatchIn(yourAccountNumber, atRangeIndex: 1)

atRangeIndex: 1中的1将提取(\d{8,})捕获组捕获的文本.

The 1 in atRangeIndex: 1 will extract the text captured by (\d{8,}) capture group.

NOTE1:如果您打算提取 8 个,并且 &l= 后只有 8 个数字,则不需要 ,限制量词,如 {8,} 表示 8 或更多.如果您打算只捕获 8 位数字,请更改为 {8}.

NOTE1: If you plan to extract 8, and only 8 digits after &l=, you do not need the , in the limiting quantifier, as {8,} means 8 or more. Change to {8} if you plan to capture just 8 digits.

注意2:NSMatchingAnchored 是您希望避免的,如果您的预期结果不在搜索范围的开头.参见 文档:

NOTE2: NSMatchingAnchored is something you would like to avoid if your expected result is not at the beginning of a search range. See documentation:

指定匹配仅限于搜索范围开头的那些.

Specifies that matches are limited to those at the start of the search range.

NOTE3:谈到最简单"事情,我建议避免使用环视,只要你不需要.环视通常会降低性能,如果您不打算捕获重叠文本,我建议使用捕获组.

NOTE3: Speaking about "simplest" things, I'd advise to avoid using look-arounds whenever you do not have to. Look-arounds usually come at some cost to performance, and if you are not going to capture overlapping text, I'd recommend to use capture groups.

我想出了一个函数,该函数将返回所有捕获组的所有匹配项(类似于 PHP 中的 preg_match_all).以下是在您的场景中使用它的一种方法:

I have come up with a function that will return all matches with all capturing groups (similar to preg_match_all in PHP). Here is a way to use it for your scenario:

func regMatchGroup(regex: String, text: String) -> [[String]] {
do {
    var resultsFinal = [[String]]()
    let regex = try NSRegularExpression(pattern: regex, options: [])
    let nsString = text as NSString
    let results = regex.matchesInString(text,
        options: [], range: NSMakeRange(0, nsString.length))
    for result in results {
        var internalString = [String]()
        for var i = 0; i < result.numberOfRanges; ++i{
            internalString.append(nsString.substringWithRange(result.rangeAtIndex(i)))
        }
        resultsFinal.append(internalString)
    }
    return resultsFinal
   } catch let error as NSError {
       print("invalid regex: \(error.localizedDescription)")
       return [[]]
   }
}
// USAGE:
let yourAccountNumber = "index.php?page=index&l=99182677"
let matches = regMatchGroup("&l=(\\d{8,})", text: yourAccountNumber)
if (matches.count > 0) // If we have matches....
{ 
    print(matches[0][1]) //  Print the first one, Group 1.
}

这篇关于如何在 Swift 中使用正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆