如何在Swift 3中使用链接(http)替换子字符串?

3

我有一个字符串和子字符串(http),我想要替换这个子字符串,但是我不知道这个子字符串什么时候结束。我的意思是想要检查它直到一个空格不再出现,然后再替换它。 我正在检查我的字符串是否包含了字符串“http”,当空格出现时,我想要进行替换。

下面是我的示例:

let string = "Hello.World everything is good http://www.google.com By the way its good". 

这是我的字符串,它也可以是动态的。上述字符串中含有http,因此我想把"http://www.google.com"替换为"网站"。 所以最终结果应该是:

string = "Hello.World everything is good website By the way its good"
2个回答

7
一种可能的解决方案是正则表达式。
该模式搜索http://https://后跟一个或多个非空白字符,直到单词边界。
let string = "Hello.World everything is good http://www.google.com By the way its good"
let trimmedString = string.replacingOccurrences(of: "https?://\\S+\\b", with: "website", options: .regularExpression)
print(trimmedString)

1
我正要发布这个帖子,但是使用正则表达式"https?://[^ ]*"。这允许同时匹配http和https。 - rmaddy
感谢您的改进。我添加了s? - vadian
好的,谢谢。还有一件事是,在https之前我想加上“网站”,并且我想保留“http”相关的内容? - Kishor Pahalwani
请编辑您的问题并添加一个具体的输入和输出示例。 - vadian
1
@kishor0011 将 with: "website" 更改为 with: "website $0" - rmaddy

1
分割每个单词,替换后再拼接即可解决此问题。
// split into array
let arr = string.components(separatedBy: " ")

// do checking and join
let newStr = arr.map { word in
    return word.hasPrefix("http") ? "website" : word
}.joined(separator: " ")

print(newStr)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接