Is there a smarter way to keep the indentation when replacing characters with a regex?

910 Views Asked by At

I want to replace the asterisks in a Markdown list with hyphens.

Example:

  • 1.0
    • 1.1
    • 1.2
  • 2
    • 2.1
      • 2.2

Currently I have a separate regex pattern for up to three levels of indentation set up in Keyboard Maestro for Mac:

Keyboard Maestro Search and Replace with a Regex Pattern

I wonder if there isn't a smarter way to do this and which adresses all kinds of indentation.

2

There are 2 best solutions below

1
On BEST ANSWER

You can use submatching groups and reference them in the replacing string like this:

Regular expression matching your lines with list items: ([\t ]*)\*(.*)

The string used for replacement: \1-\2

1
On

In many regular expression search and replace systems, you can refer to a parenthesized group in the regular expression in the replacement, using \1, \2, etc. to refer to each successive group. So for example, in sed you could do:

sed -e 's/\(^[\t ]*\)\*/\1-/'

I'm not sure if Keyboard Maestro gives you that option. It mentions that it uses ICU regular expressions; if it also uses their replacement options, then you can use $1, $2 etc. to refer to the replacement.

If not, all is not lost. You can use a lookbehind assertion to match the sequence of whitespace before the the asterisk, without including the asterisk as part of the match; then just use a single dash as your replacement:

Search for: (?<=^[\t ]*)\*
Replace with: -