gpt4 book ai didi

swift - 拆分所有字符的字符串,除了一些正则表达式

转载 作者:行者123 更新时间:2023-11-28 05:44:50 27 4
gpt4 key购买 nike

我必须将带有歌词的一长串歌曲拆分成几行,然后,对于每一行,将它们拆分成单词。我将把这些信息保存在一个二维数组中。

我见过一些类似的问题,它们已使用 [NSRegularExpression] ( https://developer.apple.com/documentation/foundation/nsregularexpression ) 解决但我似乎找不到任何等于“除了某物之外的所有东西”的正则表达式,这是我在将字符串拆分为单词时想要拆分的内容。

更具体地说,我想拆分除字母数字或'或-之外的所有内容。在 Java 中,这个正则表达式是 [^\\w'-]+

下面是字符串,后面是我的 Swift 代码以尝试完成此任务(我只是在空格上拆分,而不是用“[^\w'-]+”实际拆分单词,因为我不知道如何去做。

 1 Is this the real life?
2 Is this just fantasy?
3 Caught in a landslide,
4 No escape from reality.
5
6 Open your eyes,
7 Look up to the skies and see,
8 I'm just a poor boy, I need no sympathy,
9 Because I'm easy come, easy go,
10 Little high, little low,
11 Any way the wind blows doesn't really matter to me, to me.
12
13 Mama, just killed a man,

(等)


let lines = s?.components(separatedBy: "\n")
var all_words = [[String]]()
for i in 0..<lines!.count {
let words = lines![i].components(separatedBy: " ")
let new_words = words.filter {$0 != ""}
all_words.append(new_words)
}

最佳答案

我建议使用反向模式 [\w'-]+匹配您需要的字符串并使用 matches matching function .

您的代码将如下所示:

for i in 0..<lines!.count {
let new_words = matches(for: "[\\w'-]+", in: lines![i])
all_words.append(new_words)
}

下面一行代码:

print(matches(for: "[\\w'-]+", in: "11 Any way the wind blows doesn't really matter to me, to me."))

yields ["11", "Any", "way", "the", "wind", "blows", "doesn\'t", "really", "matter", "to", “我”, “到”, “我”].

关于swift - 拆分所有字符的字符串,除了一些正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192404/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com