我对 NSRegularExpression 在 swift 中有点困惑,有人可以帮助我吗?
task:1 given ("name","john","name of john")
然后我应该得到["name","john","name of john"]
。在这里我应该避免括号。
task:2 given ("name","john","name of john")
然后我应该得到["name","john","name of john"]
。在这里我应该避免括号和额外的空格,最后得到一个字符串数组。
task:3 给定 key = value//comment
然后我应该得到["key","value","comment"]
。在这里,我应该通过避免 =
和 //
来只获取行中的字符串
我已经为任务 1 尝试了以下代码,但没有通过。
let string = "(name,john,string for user name)"
let pattern = "(?:\\w.*)"
do {
let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.matches(in: string, options: [], range: NSRange(location: 0, length: string.utf16.count))
for match in matches {
if let range = Range(match.range, in: string) {
let name = string[range]
print(name)
}
}
} catch {
print("Regex was bad!")
}
提前致谢。
最佳答案
Swift 中的正则表达式
这些帖子可能会帮助您探索 swift 中的正则表达式:
- Does a string match a pattern?
- Swift extract regex matches
- How can I use String slicing subscripts in Swift 4?
- How to use regex with Swift?
- Swift 3 - How do I extract captured groups in regular expressions?
- How to group search regular expressions using swift?
任务 1 和 2
此表达式可能会帮助您匹配任务 1 和任务 2 所需的输出:
"(\s+)?([a-z\s]+?)(\s+)?"
基于 Rob的建议,您可以大大减少边界,例如字符列表 [a-z\s]
。例如这里,我们还可以使用:
"(\s+)?(.*?)(\s+)?"
或
"(\s+)?(.+?)(\s+)?"
简单地传递两个 " 和/或 space 之间的所有内容。
正则表达式
如果这不是您想要的表达式,您可以在 regex101.com 中修改/更改您的表达式.
正则表达式电路
您还可以在 jex.im 中可视化您的表情:
JavaScript 演示
const regex = /"(\s+)?([a-z\s]+?)(\s+)?"/gm;
const str = `"name","john","name of john"
"name"," john","name of john"
" name "," john","name of john "
" name "," john"," name of john "`;
const subst = `\n$2`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
任务 3
This expression可能会帮助你为第三个任务设计一个表达式:
(.*?)([a-z\s]+)(.*?)
const regex = /(.*?)([a-z\s]+)(.*?)/gm;
const str = `key = value // comment
key = value with some text // comment`;
const subst = `$2,`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
关于swift - swift 中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56195582/