如何从 swift 中的字符串中删除包含文本的行

How to remove a line containing text from a string in swift

我需要从字符串中删除包含特定文本的行。例如:

"这是 1 行

这是第二个

这是第 3 行,需要删除

这是一条不存在的线"

我需要删除任何包含“已删除”一词的行,以便新字符串为:

"这是 1 行

这是第二个

这是一条不存在的线"

理想情况下,它会 return 该行中包含的任何整数。所以我现在有没有删除行的字符串,以及另一个变量中的整数 3。

需要删除的行不一定符合任何结构,它们只有关键字和一个可能的整数。

我试过使用

myString.replacingOccurrences(of: "removed", with "") 

但这只会删除那个词而不是整行。

任何帮助将不胜感激,如果需要任何其他信息,请告诉我。提前谢谢你。

您可以为此使用 filter 函数:

let lines = ["this is 1 line", "this is the second", "this is line number 3 that needs to be removed", "this is a line that doesn't"]

let filteredLines = lines.filter { [=10=].contains("removed") == false }

结果:

["this is 1 line", "this is the second", "this is a line that doesn't"]

编辑:

要同时取出数字 3,试试这个:

let lines = ["this is 1 line", "this is the second", "this is line number 3 that needs to be removed", "this is a line that doesn't"]

var result:  [String] = []
var number: String = ""

lines.forEach {
    if [=11=].contains("removed") {
        if let range = [=11=].rangeOfCharacter(from: CharacterSet.decimalDigits) {
            number = String([=11=][range])
        }
    }
    else {
        result.append([=11=])
    }
}

print(number)
print(result)

结果:

3

["this is 1 line", "this is the second", "this is a line that doesn't"]