5

If I have a string, say,

"Hello, world!" 

and a regex equation that is

"world".toRegex()

and I call

"Hello, world!".replace("world".toRegex(), "universe")

I get the resulting string

"Hello, universe!"

This is all working as expected... but what if I wanted to keep a copy of that string I took out? I want to keep a copy of "world" in a variable.

2 Answers 2

12

You may use a callback to String#replace() method and assign a variable inside it:

var needle = ""
val result = "Hello, world!".replace("world".toRegex()) { needle = it.value; "universe" }
println("Replacement result: " + result)
println("Found match: " + needle)

Result:

Replacement result: Hello, universe!
Found match: world

See the online Kotlin demo.

You may use a MutableList<String> to hold a list of matches and add the matches found to it:

var needle = mutableListOf<String>()
val result = "Hello, world! This world is too small.".replace("world".toRegex()) { needle.add(it.value); "universe" }

Result:

Replacement result: Hello, universe! This universe is too small.
Found match: [world, world]

See another Kotlin demo.

Sign up to request clarification or add additional context in comments.

3 Comments

I like your solution. Anyhow it didn't helped me to use regex (\d{1,4})(\d{1,6})?(\d{1,5})? to replace 343434343434343 string to 3434-343434-34343. Any ideas on it?
@JimitPatel That is something different. Try rextester.com/IOLL50071. I do not know why you match the last two groups optionally, though.
@WiktorStribiżew cool your solution worked. Just instead of replace, I am using replaceFirst and optional group is because size is variable of the string, it is basically card number
-1
val str = "Hello, world!"
val regex = "world".toRegex()
val matchResult = regex.find(str)
val match = matchResult?.value.orEmpty()
val replaced = str.replace(regex,"universe")

2 Comments

what's wrong with this answer? just that it is not in one line?
I'm not the downvoter, but I can speculate a bit: (1) this code does two passes on the input, and (2) generally code-only answers are frowned upon. Even if the code seems totally obvious to you, a bit of exposition and explanation or a link to the docs goes a long way to making an answer high-quality. Also, (3) sometimes downvotes happen for arbitrary reasons that you needn't worry about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.