0

I am trying to reformat a string to my desired format. I have been trying to figure this out for a while but I can't think of any elegant solution using regexs. I have come up with a solution using String's indexOf() and replace() but it's not exactly pretty.

I want to convert any string so that there is exactly one space on each side of the "-".

Possible inputs:

"abc- abc"
"abc -abc"
"abc - abc"
"abc-abc" 

and each case should be converted to

"abc - abc"

Thanks for any help. Let me know if you need more clarification.

1
  • Even if your initial solution wasn't pretty, you should still show it as part of the question. It demonstrates that you at least tried something. Commented Jul 18, 2013 at 3:08

3 Answers 3

2

Using \s*-\s* pattern:

"abc- abc".replaceAll("\\s*-\\s*", " - "))
Sign up to request clarification or add additional context in comments.

Comments

1

Using String#replaceAll:

String pattern = "\\s*-\\s*";
String s1 = "abc- abc";
String s2 = "abc -abc";
String s3 = "abc - abc";
String s4 = "abc-abc";
System.out.println(s1.replaceAll(pattern, " - "));
System.out.println(s2.replaceAll(pattern, " - "));
System.out.println(s3.replaceAll(pattern, " - "));
System.out.println(s4.replaceAll(pattern, " - "));

Explanation of "\\s*-\\s*" regex:

  • \\s => space (in fact, is \s but Java needs double \\)
  • * => 0 or more
  • - => simple '-'

More info about Regular Expressions: Regular Expression Basic Syntax Reference

1 Comment

doh, I'm an idiot. I was using \\S instead of \\s which is why mine wasn't working.
1

The simplest would probably be to use this pattern:

[ ]?-[ ]?

Like this:

str = str.replaceAll("[ ]?-[ ]?", " - ");

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.