问题描述:

Is there a way to add a character, say '\t', at specific position of the string?

For example:

String str = "key1=123 key2=text with spaces key3=foo";

I need to replace all spaces before keys with tabs in the key value pair string.

Note that some values may contain spaces.

网友答案:

Use a look ahead:

str = str.replaceAll(" (?=\\w+=)", "\t");

or similar, capture the key and put it back:

str = str.replaceAll(" (\\w+=)", "\t$1");
相关阅读:
Top