0

I am having a String:

String str = "sourceType=Match, msg=Event yyuyu, test 1, usrPicture=null, friendCount=0";

Now I am writing a regex expression to replace value for "msg" with "...." My regex looks like:

str.replaceAll("(\\smsg=)(.+?)(,)", "$1...$3");

As per my above regex it matches till:

msg=Event yyuyu,

but I want it to match till:

msg=Event yyuyu, test 1,

Basically It should match till last "," (By this I mean it should match till last "," for value of key "msg"). I tried to put some regex after (,). But it's not working. Any help on this will be really appreciated.

5
  • Check msg=(.*?),\s*\S+= Commented Mar 2, 2017 at 4:24
  • Because I want the result like: msg=.... Commented Mar 2, 2017 at 4:25
  • @Tushar as per your regex it matches till: msg=Event yyuyu, test 1, usrPicture= Commented Mar 2, 2017 at 4:29
  • You need to extract Group 1 using $1 or \1. Commented Mar 2, 2017 at 5:01
  • is usrPicture always the next attribute after msg? Commented Mar 2, 2017 at 5:51

2 Answers 2

3

The problem is, you are saying to match as minimum characters as possible by adding ? in (.+?). Try removing it.

 str.replaceAll("(\\smsg=)(.+)(,)", "$1...$3");

Moreover, you mentioned you want to match till last , so it should match till

msg=Event yyuyu, test 1, usrPicture=null,

not till

msg=Event yyuyu, test 1,

as you specified in your question.

See this https://regex101.com/r/BCNsTt/1

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

Comments

0

If you want to match till the next attribute (usrPicture) as in your example, not as in your question, then you can try the following regex

(\smsg=)(.+?)(,)(\s\w+=)

Replace with $1...$3$4

Output:

sourceType=Match, msg=..., usrPicture=null, friendCount=0

Demo can be found here

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.