swift - 除一些使用正则表达式的字符外,在所有字符上拆分字符串
问题描述
我必须将带有歌词的长字符串分成几行,然后对于每一行,将它们分成单词。我将把这些信息保存在一个二维数组中。
我见过一些类似的问题,他们已经使用 [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,
(ETC。)
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
匹配功能。
您的代码将如下所示:
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."))
产量["11", "Any", "way", "the", "wind", "blows", "doesn\'t", "really", "matter", "to", "me", "to", "me"]
。
推荐阅读
- android - 更改数据库版本后如何保留表值?
- python - ValueError at /Add invalid literal for int() with base 10: 'O'
- c++ - 重载 << 运算符以将“”更改为“\n”
- node.js - 如何将 html 的字符串作为 html 文件发送?
- angular - 需要帮助编写打印功能的茉莉花单元测试用例
- html - 使用 SASS 对具有相同类的元素应用不同的动画
- java - Java 定义了一个显式的包私有修饰符
- clang - Clang AST 匹配器:`operator()` 没有 CXXMethodDecl?
- java - JUnit 测试不让我知道测试是通过还是失败
- java - firebase - php - 向所有人发送通知