swift3 String.range(of:返回nil

时间:2017-06-12 20:00:49

标签: string swift3 range

" myDRange"如果值中没有小数,则语句将返回一个范围。如果有小数,则返回nil。其他语句按预期返回范围。我做错了什么?

Swift3 - myDRange返回nil

var pseudoXML = "<d>4.0</d><rs>Test</rs><o>0</o>"
let myDRange = pseudoXML.range(of: "(?<=<d>)[^.]+(?=</d>)", options: .regularExpression)
let myRSRange = pseudoXML.range(of: "(?<=<rs>)[^.]+(?=</rs>)", options: .regularExpression)
let myORange = pseudoXML.range(of: "(?<=<o>)[^.]+(?=</o>)", options: .regularExpression)

Swift3 - myDRange返回范围

var pseudoXML = "<d>40</d><rs>Test</rs><o>0</o>"
let myDRange = pseudoXML.range(of: "(?<=<d>)[^.]+(?=</d>)", options: .regularExpression)
let myRSRange = pseudoXML.range(of: "(?<=<rs>)[^.]+(?=</rs>)", options: .regularExpression)
let myORange = pseudoXML.range(of: "(?<=<o>)[^.]+(?=</o>)", options: .regularExpression)

TIA

1 个答案:

答案 0 :(得分:0)

@CMan,

要使myDRange需要工作,请使用以下正则表达式&#34; (?<=<d>)([0-9](\\.[0-9]))+(?=</d>)&#34;

这将解决myDRange

的零问题

您的工作代码示例:

var pseudoXML = "<d>4.0</d><rs>Test</rs><o>0</o>"
let myDRange = pseudoXML.range(of: "(?<=<d>)([0-9](\\.[0-9]))+(?=</d>)", options: .regularExpression)
let myRSRange = pseudoXML.range(of: "(?<=<rs>)[^.]+(?=</rs>)", options: .regularExpression)
let myORange = pseudoXML.range(of: "(?<=<o>)[^.]+(?=</o>)", options: .regularExpression)