Skip to content

正则表达式中的 "?:" 的作用 #17

Description

@ScoutYin

(?:x) 匹配 'x' 但是不记住匹配项,因此也不能反向引用该匹配值,这种叫作非捕获括号

const reg1 = /(\w+),(\d+),(\w+)/
const reg2 = /(?:\w+),(?:\d+),(\w+)/
const str = 'abc,123,de'

str.match(reg1)
// ["abc,123,de", "abc", "123", "de"]
str.replace(reg1, '$1哈哈$2哈哈$3') // $n (n是一个数字,表示第n个捕获组的内容)
// "abc哈哈123哈哈de"

str.match(reg2)
// ["abc,123,de",  "de"]
str.replace(reg1, '$1哈哈$2哈哈$3')
// "de哈哈$2哈哈$3"

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions