1

I have a CSV file like

Data
Dun&BradStreet
Dunkin & Donut

Here Data is the 'header' of the column.

I am using the encoding and replacement as

 String encodedUrl = URLEncoder.encode(data[i], "UTF-8");
 String data = encodedUrl.replaceAll("%2B","+");

Desired Result

Data
Dun&BradStreet
Dunkin+%26+Donut

Output

 Data
 Dun%26BradStreet
 Dunkin+%26+Donut

How to keep '&' if there are no spaces when '&' is present? Any help is appreciated. Thanks in advance.

3
  • Are you going to put this information in a URL? If so, the & should be encoded per ietf.org/rfc/rfc1738.txt unless you are using it in a special way (like separating name-value pairs). If you are not putting it in a URL, why are you using URLEncoder.encode on it? Commented Apr 6, 2014 at 4:34
  • @lreeder : Yes I am going to put in an URL. So that is why I need to know how to do the encoding without replacing '&' as in the first case? I appreciate any help. Commented Apr 6, 2014 at 4:51
  • 1
    if you want to put the first value also in the URL it also needs to be encoded. Commented Apr 6, 2014 at 4:53

2 Answers 2

1

You can try this one if there are one or more times spaces before and after &.

here \\s+ represents one or more times spaces. Read more about Java Regex Pattern.

String str = data[i].replaceAll("\\s+&\\s+", "+%26+");
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it with replace() like so,

String in = "Data\nDun&BradStreet\nDunkin & Donut";
System.out.println(in.replace(" & ", "+%26+"));

Output is "Desired Result" -

Data
Dun&BradStreet
Dunkin+%26+Donut

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.