Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift正则表达式捕获组难度_Swift_Regex - Fatal编程技术网

Swift正则表达式捕获组难度

Swift正则表达式捕获组难度,swift,regex,Swift,Regex,试图算出一个正则表达式。输出是零星的。对于我的三个命名捕获组中的每一个,每个捕获组在不同的位置都至少有一个nil值,有时捕获组出现故障。我已经查过了,但到目前为止运气不好,所以我想我会问 基本上,我的文本文件包含一组十六进制,它们组合起来形成渐变。我需要在文件中刮取的相关内容如下所示,在整个文件中定期重复: 002 Tropic Thunder #a18cd2|#fbc4eb 首先,我一直在读rtf文件: if let rtfPath = Bundle.main.url(forReso

试图算出一个正则表达式。输出是零星的。对于我的三个命名捕获组中的每一个,每个捕获组在不同的位置都至少有一个nil值,有时捕获组出现故障。我已经查过了,但到目前为止运气不好,所以我想我会问

基本上,我的文本文件包含一组十六进制,它们组合起来形成渐变。我需要在文件中刮取的相关内容如下所示,在整个文件中定期重复:

002 Tropic Thunder 


#a18cd2|#fbc4eb

首先,我一直在读rtf文件:

if let rtfPath = Bundle.main.url(forResource: "mytextfile", withExtension: "rtf") {
    do {
        let attributedStringWithRtf: NSAttributedString = try NSAttributedString(url: rtfPath, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
        self.testString = attributedStringWithRtf
    } catch let error {
         print("Got an error \(error)")
    }
}
let myString = self.testString?.string
接下来,我创建模式,调用我的函数,并打印结果:

do {
    pattern = try NSRegularExpression(pattern: "[0-9]{3}\\s*(?<gradientName>[a-zA-Z]{2,11}\\s[a-zA-Z]{2,11})\\s*(?<hexCode1>#[0-9a-fA-F]{6})|(?<hexCode2>#[0-9a-fA-F]{6})")
} catch {
    print(error)
}
        
let result = namedCaptureGroupsInMatches(of: pattern!, against: myString!)
       
print(result)
do{
pattern=try NSRegularExpression(模式:“[0-9]{3}\\s*(?[a-zA-Z]{2,11}\\s[a-zA-Z]{2,11})\\s*(?#[0-9a-fA-F]{6})(?#[0-9a-fA-F]{6}”)
}抓住{
打印(错误)
}
让result=namedCaptureGroupsInMatches(of:pattern!,反对:myString!)
打印(结果)
我的函数如下所示:

func namedCaptureGroupsInMatches(of regularExpression:NSRegularExpression, against string:String) -> [[String:Substring?]] {
    let names = namedCaptureGroups(inRegularExpression: regularExpression)

    let ms = regularExpression.matches(in: string, options: [],
                                         range:NSRange(string.startIndex..<string.endIndex,
                                                       in:string))
    return ms.map({ (tcr:NSTextCheckingResult) -> [String:Substring?] in
        let keyvalues = names.map({ (name:String) -> (String,Substring?) in
            let captureGroupRange = tcr.range(withName: name)
            if captureGroupRange.location == NSNotFound {
                return (name,nil)
            } else {
                return (name,string[Range(captureGroupRange, in: string)!])
            }
        })

        return Dictionary(uniqueKeysWithValues: keyvalues)
    })
}
func namedCaptureGroupsInMatches(正则表达式的:NSRegularExpression,与字符串:字符串匹配)->[[字符串:子字符串?]]{
let names=namedCaptureGroups(在regularExpression:regularExpression中)
让ms=regularExpression.matches(in:string,options:[],
范围:NSRange(string.startIndex..[string:Substring?]in
让keyvalues=names.map({(名称:String)->(String,Substring?)在
让captureGroupRange=tcr.range(使用名称:name)
如果captureGroupRange.location==NSNotFound{
报税表(姓名,无)
}否则{
返回(名称,字符串[范围(captureGroupRange,in:string)!)
}
})
返回字典(UniqueKeyWithValues:keyvalues)
})
}
func namedCaptureGroups(在regularExpression正则表达式中:NSRegularExpression)->[字符串]
{
让regexString=regularExpression.pattern
让captureGroupNames=try!NSRegularExpression(模式:“\\”(\\?\\”,选项:[]))
让groupNameMatches=captureGroupNames.matches(在:regexString中,选项:[],
范围:NSRange(regexString.startIndex..String in
return(regexString作为NSString).substring(带:textCheckingResult.range(at:1))
}
返回名称
}

有什么想法吗?

您的问题是您没有逃逸
|
,因此它被解释为备选方案(与“或”相同),并且您的完全匹配将不包括第二个六边形。您只需逃逸它就可以逐字匹配:

let pattern = #"[0-9]{3}\s*(?<gradientName>[a-zA-Z]{2,11}\s[a-zA-Z]{2,11})\s*(?<hexCode1>#[0-9a-fA-F]{6})\|(?<hexCode2>#[0-9a-fA-F]{6})"#
do {
    let regex = try NSRegularExpression(pattern: pattern)
    let result = namedCaptureGroupsInMatches(of: regex, against: myString)     
    print(result)
} catch {
    print(error)
}
let模式=#“[0-9]{3}\s*(?[a-zA-Z]{2,11}\s[a-zA-Z]{2,11})\s*(?#[0-9a-fA-F]{6})\|(?#[0-9a-fA-F]{6})”#
做{
让regex=尝试NSRegularExpression(模式:模式)
让result=namedCaptureGroupsInMatches(of:regex,反对:myString)
打印(结果)
}抓住{
打印(错误)
}

与你的问题无关,但hexa应该是
0-9a-fA-F
好吧,也许可以在以后的某个时候为我保留一些面子和一点表现,就是这样。干杯Leo。Noob帐户…还不能+1,但我会记得。namedCaptureGroups方法声明在哪里?我们在VC中有它。因此,将与你的问题相关的内容添加到你的帐户中非常好!再次感谢!见鬼,是的。感谢lmk。
let pattern = #"[0-9]{3}\s*(?<gradientName>[a-zA-Z]{2,11}\s[a-zA-Z]{2,11})\s*(?<hexCode1>#[0-9a-fA-F]{6})\|(?<hexCode2>#[0-9a-fA-F]{6})"#
do {
    let regex = try NSRegularExpression(pattern: pattern)
    let result = namedCaptureGroupsInMatches(of: regex, against: myString)     
    print(result)
} catch {
    print(error)
}