NSRegularExpression中命名的捕获组 - 获取范围的组名称 [英] Named capture groups in NSRegularExpression - get a range's group's name
问题描述
Apple称NSRegularExpression基于ICU正则表达式库: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/
Apple says that NSRegularExpression is based on the ICU Regular Expression library: https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/
模式目前支持的语法是ICU指定的语法。 ICU正则表达式在 http://userguide.icu-project.org/strings/regexp 。
该页面(在icu-project.org上)声称现在支持命名捕获组,使用相同的语法作为.NET正则表达式:
That page (on icu-project.org) claims that Named Capture Groups are now supported, using the same syntax as .NET Regular Expressions:
(?< name> ...)
命名捕获组。<尖括号>
是字面值 - 它们出现在模式中。
(?<name>...)
Named capture group. The<angle brackets>
are literal - they appear in the pattern.
我编写了一个程序,它获得了一个看似正确的多个范围的匹配 - 尽管每个范围都返回两次(原因未知) - 但我唯一的信息是范围索引及其文本范围。
I have written a program which gets a single match with multiple ranges which seem correct - though each range is returned twice (for reasons unknown) - but the only information I have is the range's index and its text range.
例如,正则表达式: ^(?< foo> foo)\。(?< bar> bar)\。(?< bar2> ; baz)$
,测试字符串 foo.bar.baz
For example, the regex: ^(?<foo>foo)\.(?<bar>bar)\.(?<bar2>baz)$
with test string foo.bar.baz
给我这些结果:
Idx Start Length Text
0 0 11 foo.bar.baz
1 0 3 foo
2 4 3 bar
3 8 3 baz
有没有办法知道 baz
来自捕获组 bar2
?
Is there any way to know that "baz
" came from the capture-group bar2
?
推荐答案
由于支持iOS11命名的捕获组。 NSTextCheckingResult
具有 open func range(withName name:String) - > NSRange
。
Since iOS11 named capture groups are supported. NSTextCheckingResult
has the function open func range(withName name: String) -> NSRange
.
使用正则表达式: ^(?< foo> foo)\。 (?< bar> bar)\。(?< bar2> baz)$
,测试字符串 foo.bar.baz
给出4结果匹配。函数 match.range(withName:bar2)
返回字符串的范围 baz
Using the regex: ^(?<foo>foo)\.(?<bar>bar)\.(?<bar2>baz)$
with the test string foo.bar.baz
gives 4 result matches. The function match.range(withName: "bar2")
returns the range for the String baz
这篇关于NSRegularExpression中命名的捕获组 - 获取范围的组名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!