Put an underscore before all digits in a string

I’ve tried reading these docs Introducing Julia/Strings and characters - Wikibooks, open books for an open world and these docs Strings · The Julia Language 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