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.
2 Answers 2
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
Comments
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
msg=(.*?),\s*\S+=1ドルor1円.usrPicturealways the next attribute aftermsg?