3

I've almost got a regex question figured out, just one little thing.

I am trying to get this:

and so use [chalk](#api).red(string[, options])

Into this:

and so use chalk.red(string[, options])

I have this:

var md = 'and so use chalk.red(string[, options])';
console.log(md.replace(/(\[.*?\]\()(.+?)(\))/g, '$1'))

Which matches the [x](y) perfectly. However, $1 returns [chalk](. I would like it to return chalk instead, and I'm stumped on how to do this.

I might(?) have figured it out:

Does this do the trick in all cases?

/(\[(.*?)\]\()(.+?)(\))/g
David Bradshaw
  • 11,859
  • 3
  • 41
  • 70
dthree
  • 19,847
  • 14
  • 77
  • 106

2 Answers2

2

Lets take a look at what your current regex does

/(\[(.*?)\]\()(.+?)(\))/g
1st Capturing group (\[(.*?)\]\()
    \[ matches the character [ literally
    2nd Capturing group (.*?)
        .*? matches any character (except newline)
            Quantifier: *? Between zero and unlimited times, as few times as possible, expanding as needed [lazy]
    \] matches the character ] literally
    \( matches the character ( literally
3rd Capturing group (.+?)
    .+? matches any character (except newline)
        Quantifier: +? Between one and unlimited times, as few times as possible, expanding as needed [lazy]
4th Capturing group (\))
    \) matches the character ) literally

As you can see your 1st capture group contains your 2nd capture group. The 2nd capture group is chalk and your first is [chalk](.

  1. You could change your javascript to read console.log(md.replace(/(\[.*?\]\()(.+?)(\))/g, '$2'))
  2. rewrite your regex to remove the parenthesis that capture the brackets so your only capturing whats inside them. \[(.*?)\]\((.+?)\)

If your new to regular expressions I would highly recommend a regex tool such as regex101.com to see what your groups are and what exactly your regex is doing.

Heres your regex I saved for you https://regex101.com/r/tZ6yK9/1

ug_
  • 11,267
  • 2
  • 35
  • 52
0

Use this RegExp:

/\[([^\]]+)\][^\)]+\)/g

and if you call this

'and so use [chalk](#api).red(string[, options])'.replace(/\[([^\]]+)\][^\)]+\)/g, '$1')

it returns this

"and so use chalk.red(string[, options])"

smnbbrv
  • 23,502
  • 9
  • 78
  • 109