[英]Swift Get String before Substring
I have a string, this string changes constantly.我有一个字符串,这个字符串不断变化。
I grab a part of my string which in code can be called let mySub = "xyz"
我抓住了我的字符串的一部分,在代码中可以调用let mySub = "xyz"
The original string is something that is changing over time, so dont worry how I get mySub
for this example lets say the string is let baseString = 123123xyz1234
原始字符串会随着时间的推移而变化,所以不要担心我如何得到这个例子的mySub
假设字符串是let baseString = 123123xyz1234
How would I be able to grab a substring of everything before xyz
without it being hard coded so the position of xyz
can be different and the substring grabbing still works correctly?我如何能够在xyz
之前抓取所有内容的 substring 而无需对其进行硬编码,因此xyz
的 position 可以不同并且 substring 抓取仍然可以正常工作?
You can find first matching range of mySub
in baseString
, and if found, get previous part.您可以在baseString
中找到mySub
的第一个匹配范围,如果找到,则获取上一部分。
let baseString: String = "123123xyz1234"
let mySub = "xyz"
if let range = baseString.range(of: mySub) {
let beforeStr = baseString[..<range.lowerBound]
}
You can get the lowerbound index of the range of your substring and get the substring upTo that index.您可以获取 substring 范围的下限索引,并将 substring 获取到该索引。 If you would like to make a caseInsensitive of diacritic insensitive search you can use localizedStandardRange:如果您想对变音符号不敏感搜索进行不区分大小写,可以使用本地化标准范围:
extension StringProtocol {
func substring<S: StringProtocol>(upTo string: S, options: String.CompareOptions = []) -> SubSequence? {
guard let lower = range(of: string, options: options)?.lowerBound
else { return nil }
return self[..<lower]
}
func localizedStandardSubstring<S: StringProtocol>(upTo string: S, options: String.CompareOptions = []) -> SubSequence? {
guard let lower = localizedStandardRange(of: string)?.lowerBound
else { return nil }
return self[..<lower]
}
}
let string = "123123xyz1234"
if let substring = string.substring(upTo: "xyz") {
print(substring) // "123123\n"
}
let localized = "123123café1234"
if let substring = localized.localizedStandardSubstring(upTo: "CAFE") {
print(substring) // "123123\n"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.