0

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.

7
  • Try something out. Create JSFiddle and share it here. Commented Jan 5, 2017 at 11:54
  • I tried to split the KV pair based in space but I couldn't as there are space in some of the values. not familiar with the REGEX can you help. Commented Jan 5, 2017 at 11:56
  • 1
    Follow this excellent link Commented Jan 5, 2017 at 11:56
  • 1
    Your question is pretty unclear. It sounds like you don't actually know the specific position (that would suggest you know the index already). Instead, it's defined in terms of "every key position" - which you haven't clearly defined. Can your values include = signs? Commented Jan 5, 2017 at 12:00
  • Most probably you will be succeeded with String.replaceAll() method Commented Jan 5, 2017 at 12:09

1 Answer 1

1

Use a look ahead:

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

or similar, capture the key and put it back:

str = str.replaceAll(" (\\w+=)", "\t$1");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that really helped.

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.