swift - swift 中的正则表达式

标签 swift regex regex-group regex-greedy nsregularexpression

我对 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 中的正则表达式:

任务 1 和 2

此表达式可能会帮助您匹配任务 1 和任务 2 所需的输出:

"(\s+)?([a-z\s]+?)(\s+)?"

enter image description here


基于 Rob的建议,您可以大大减少边界,例如字符列表 [a-z\s]。例如这里,我们还可以使用:

"(\s+)?(.*?)(\s+)?"

"(\s+)?(.+?)(\s+)?"

简单地传递两个 " 和/或 space 之间的所有内容。

enter image description here

正则表达式

如果这不是您想要的表达式,您可以在 regex101.com 中修改/更改您的表达式.

正则表达式电路

您还可以在 jex.im 中可视化您的表情:

enter image description here

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]+)(.*?)

enter image description here

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/

相关文章:

正则表达式 optional 组

php - 无法通过 http 将 base64 图像内容 POST 到 PHP 服务器

swift - 协议(protocol)扩展 : cannot assign to get-only property

swift - 明暗不切换,分段控制(Swift)

arrays - swift 数组 : Cannot invoke 'append' with an argument list of type '(Int)'

regex - 在正则表达式中使用变量

python - 从 csv 返回 python 中的多个值

regex - 防止危险的正则表达式停止应用程序

正则表达式用于匹配除两个单词之间的文本之外的所有内容

javascript - 由于尖号 (#) 字符,javascript 正则表达式捕获中缺少字符