当前位置: 动力学知识库 > 问答 > 编程问答 >

java - add character to a string at specific place based on Regular expression

问题描述:

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");
分享给朋友:
您可能感兴趣的文章:
随机阅读: