Reputation: 731
I want to replace an occurrence of a lowercase in a string followed by a period followed by an uppercase (without any space) to contain a space also.
For example:
...inconvenient.The...
gets converted to
...inconvenient. The...
What is an approach for this in Java, possibly using regex?
Upvotes: 0
Views: 144
Reputation: 70732
I assume you want to insert a space character after a lowercase and a dot if it's followed by an uppercase..
String s = "foo.Bar and bar.Baz but not FOO.BAR or BAR.baz";
s = s.replaceAll("(?<=[a-z]\\.)(?=[A-Z])", " ");
System.out.println(s); //=> "foo. Bar and bar. Baz but not FOO.BAR or BAR.baz"
Explanation:
(?<= # look behind to see if there is:
[a-z] # any character of: 'a' to 'z'
\. # '.'
) # end of look-behind
(?= # look ahead to see if there is:
[A-Z] # any character of: 'A' to 'Z'
) # end of look-ahead
Upvotes: 3
Reputation: 41838
Just this:
result = subject.replace(/([a-z]\.)([A-Z])/g, "$1 $2");
Explain Regex
( # group and capture to \1:
[a-z] # any character of: 'a' to 'z'
\. # '.'
) # end of \1
( # group and capture to \2:
[A-Z] # any character of: 'A' to 'Z'
) # end of \2
Upvotes: 0