Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression how to search for () and replace with[]

Silly question, but I do not know how to find (2000) into a regular expression and replace it with [2000]

like image 801
Sam Avatar asked Dec 12 '25 04:12

Sam


1 Answers

You can do:

str.replace(/\((\d+)\)/g, "[$1]");

Regex used: \((\d+)\)

  • ( and ) are special char in regex used for grouping, to match literal ( ), you need to escape them as \( \)
  • \d is short for a digit. \d+ means one or more digits.
  • ( ) is to group and remember the number. The remembered number will later be used in replacement.
  • g for global replacement. Mean every occurrence of the patten in the string will be replaced.
  • $1 is the number between ( )that was grouped and remembered.
  • / / are the regex delimiters.
like image 92
codaddict Avatar answered Dec 14 '25 17:12

codaddict