I'm trying to parse the location entries from a .ics file as follows seen in the image below . Normally this works fine even though the only tester I can find is PCRE rather than ICU as I just need to add an extra backslash to any special characters.
我正在尝试解析.ics文件中的位置条目,如下图所示。通常情况下这很好,即使我能找到的唯一的测试人员是PCRE而不是ICU,因为我只需要为任何特殊字符添加额外的反斜杠。
However in swift I get the following results:
但是在swift中我得到以下结果:
"^Location" //No Match
"^VERSION" //No Match
"^BEGIN" //Match
"^ :" //Match
Can I get the '^' anchors to function like they do in the PCRE tester?
我可以让'^'锚定器像PCRE测试仪一样运行吗?
PCRE正则表达式测试仪
Code
func testParticipantParsing()
{
//let locationRegex = "^LOCATION:(.*(?:\\n :?.*)*)"
let locationRegex = "LOCATION:(.*(?:\\n :?.*)*)"
var regex : NSRegularExpression! = nil
var resultsArray = [String]()
//Parse for location
do
{
regex = try NSRegularExpression(pattern: locationRegex, options: NSRegularExpressionOptions.init(rawValue: 0))
let nsString = content as NSString
let results = regex.matchesInString(content, options: [], range: NSMakeRange(0, nsString.length))
resultsArray = results.map{ nsString.substringWithRange($0.range) }
}
//Catch errors if regex fails
catch
{
print("invalid regex")
}
//Strip .ics new line tokens
for var result in resultsArray
{
result = result.stringByReplacingOccurrencesOfString("\n :", withString: "")
result = result.stringByReplacingOccurrencesOfString("\n ", withString: "")
print(result)
}
}
1 个解决方案
#1
1
Just add the (?m)
at the start of your pattern.
只需在模式的开头添加(?m)即可。
let locationRegex = "(?m)^LOCATION:(.*(?:\\n :?.*)*)"
^^^^
The (?m)
is the inline modifier version of the MULTILINE modifier that forces ^
to match the location at the beginning of a line rather than string (and makes $
match the location at the end of the line, before the newline sequence).
(?m)是MULTILINE修饰符的内联修饰符版本,它强制^匹配行开头的位置而不是字符串(并且在换行符序列之前使$匹配行末尾的位置)。
见表4:标志选项:
m
flag:
Control the behavior of^
and$
in a pattern. By default these will only match at the start and end, respectively, of the input text. If this flag is set,^
and$
will also match at the start and end of each line within the input text.m flag:控制模式中^和$的行为。默认情况下,这些只会分别匹配输入文本的开头和结尾。如果设置了此标志,则^和$也将匹配输入文本中每行的开头和结尾。
#1
1
Just add the (?m)
at the start of your pattern.
只需在模式的开头添加(?m)即可。
let locationRegex = "(?m)^LOCATION:(.*(?:\\n :?.*)*)"
^^^^
The (?m)
is the inline modifier version of the MULTILINE modifier that forces ^
to match the location at the beginning of a line rather than string (and makes $
match the location at the end of the line, before the newline sequence).
(?m)是MULTILINE修饰符的内联修饰符版本,它强制^匹配行开头的位置而不是字符串(并且在换行符序列之前使$匹配行末尾的位置)。
见表4:标志选项:
m
flag:
Control the behavior of^
and$
in a pattern. By default these will only match at the start and end, respectively, of the input text. If this flag is set,^
and$
will also match at the start and end of each line within the input text.m flag:控制模式中^和$的行为。默认情况下,这些只会分别匹配输入文本的开头和结尾。如果设置了此标志,则^和$也将匹配输入文本中每行的开头和结尾。