Put an underscore before all digits in a string

I’ve tried reading these docs https://en.wikibooks.org/wiki/Introducing_Julia/Strings_and_characters and these docs https://docs.julialang.org/en/v1/base/strings/#Base.@s_str and I’ve tried several things, such as:

replace("x1", r"\d+" => s"_\1")

which returns:

PCRE error: unknown substring

. And:

replace("x1", r"[0-9]+" => s"_\1")

which returns:

PCRE error: unknown substring

. I’ve also tried:

replace("x1", r"[0-9]+" => s"_\g")

which returns:

Bad replacement string: _\g

. And:

replace("x1", r"\d+" => SubstitutionString("_\\1"))

which returns:

PCRE error: unknown substring

. And:

replace("x1", r"\d+" => SubstitutionString("_\\g"))

which returns:

Bad replacement string: _\g

Must admit I’m kind of stumped for what to do. Any ideas?

In case my question is unclear, what I’m expecting is the output “x_1”.

I think what you’re missing is that \1 refers to the first capture in the regex match, and to create a capture you need to use parentheses in the regex:

julia> replace("x123y456", r"(\d+)" => s"_\1")
"x_123y_456"

(note the parentheses around \d+)

7 Likes