Is there some way to do a `Regex.replaceEntire`? I...
# getting-started
y
Is there some way to do a
Regex.replaceEntire
? I'm aware of
matchEntire
, but I want to be able to use references to capture groups in the replacement string. Is there some easy way to use a
MatchResult
for constructing a string where it aptly resolves capture group references? EDIT: solved! Just use
^...$
lol! Question is, is there a way to take a regex and turn it into that form programmatically?
j
I think you're looking for this one:
Copy code
inline fun CharSequence.replace(
    regex: Regex, 
    noinline transform: (MatchResult) -> CharSequence
): String
y
I don't see how to take a
MatchResult
and construct a replacement string easily by replacing the capture group references
j
You can read the capturing group values from the match result, and use the whole matched string from the match result as well. So you can replace in the matched string each group
y
Yeah but that involves parsing the replacement string (e.g.
"$1$2${foo}"
) to replace those references, while also supporting escapes thru backslashes etc. Seems to me like there should be a built-in solution
j
Sorry I might have misunderstood what you need. There are multiple overloads of this. If you want to pass a replacement string, use the overload that takes a regex and a replacement string. If you want more control, use the one I mentioned with the function that takes a match result. Could you please give an example of what you want to achieve?
(Ah I just saw your edit, I missed that you wanted to apply your regex on the entire string, not process each match)
y
I have a regex that I want to match the entire string fully. There is no
replaceEntire
function, so my options are to either modify the regex, or to use
matchEntire
and manually process the replacement string to deal with capture group references. I think I'll go with modifying the regex for now! But I'm still curious to hear if any other options exist
j
I see. So yeah you can use
replace
with a regex that matches the start and end of input. You could also construct a new regex that enforces this programmatically, but that might require some carefulness with whether the original ends with a backslash or something.
v
Just use ^...$ lol! Question is, is there a way to take a regex and turn it into that form programmatically?
Use a non-capturing group.
^(?:originalRegexHere)$
thank you color 1
The original regex can also itself contain start of string or end of string anchors, will work the same
e
^$ do not necessarily match start/end in multiline mode, there are \A and \Z which do
v
Well, depends on the regex engine. JavaScript for example does not support those.