【问题标题】:Regex to capture the first 5 groups and last character正则表达式捕获前 5 个组和最后一个字符
【发布时间】:2020-08-15 03:05:17
【问题描述】:

我正在尝试创建一个正则表达式,它将提取字符串中的前 5 个字符和最后一个字符,而不管字符串的大小。例如

对于FOO:BAR:123FF:FOO:BARF:OO:BAR:1234FOO:BAR:123FF:FOO:BAR:FOO:BAR:FOO:BAR:FOO:1234,它将捕获六个组,即FOO BAR 123FF FOO BAR 1234

【问题讨论】:

标签: regex regex-group capturing-group


【解决方案1】:

如果你的字符串总是这样格式化,我认为最好使用split

let a = 'FOO:BAR:123FF:FOO:BAR:FOO:BAR:FOO:BAR:FOO:1234'
let res = a.split(':')
// Remove all between the 5th and the last element
res.splice(5, res.length - 5 - 1)

console.log(res)

但如果你真的想用正则表达式,也是可以的:

let a = 'FOO:BAR:123FF:FOO:BAR:FOO:BAR:FOO:BAR:FOO:1234'
let regex = /^(\w+):(\w+):(\w+):(\w+):(\w+):.*:(\w+)$/

console.log(regex.exec(a).slice(1))

【讨论】:

    【解决方案2】:

    您可以使用下面的正则表达式获取所有分隔的单词:

    const regex = /[^:]*\w+/g
    

    之后,您可以通过以下方式获取所有匹配项:

    const text = "FOO:BAR:123FF:FOO:BAR:FOO:BAR:FOO:BAR:FOO:1234"
    const matches = text.match(regex)
    

    最后删除重复项:

    const uniqueArr = Array.from(new Set(matches))
    console.log(uniqueArr) // ["FOO", "BAR", "123FF", "FOO", "BAR", "1234"]
    

    希望对您有所帮助! :)

    【讨论】:

    • 如果第 6 次和最后一次之间没有重复怎么办?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2014-08-12
    • 2019-03-21
    • 2014-07-18
    相关资源
    最近更新 更多