0

Can someone please help with regex for replacing all integers and doubles with in a given String with single quotes : Key1=a,Key2=2,Key3=999.6,Key4=8888,Key5=true

with this : Key1=a,Key2='2',Key3='999.6',Key4='8888',Key5=true

I would like to use regex group capturing rules to replace all numeric string startng after = and replace with ''.

2 Answers 2

1

Use a look arounds each end:

String quoted = str.replaceAll("(?<==)\\d+(\\.\\d+)?(?=,|$)", "'$0'");

The entire match, which is group 0, is the number to be replaced by quotes around group 0.

The match starts with a look behind for an equals and ends with a look ahead for a comma or end of input.

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

Comments

1

You may try a regex replace all approach here:

String input = "Key1=a,Key2=2,Key3=999.6,Key4=8888,Key5=true";
String output = input.replaceAll("([^,]+)=(\\d+(?:\\.\\d+)?)", "$1='$2'");
System.out.println(output);  // Key1=a,Key2='2',Key3='999.6',Key4='8888',Key5=true

Here is an explanation of the regex pattern used:

([^,]+)             match and capture the key in $1
=                   match =
(\\d+(?:\\.\\d+)?)  match and capture an integer or float number in $2

Then, we replace with $1='$2', quoting the number value.

Comments

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.