aceBox
aceBox

Reputation: 731

What will be the regex for replacing lowercase followed by period followed by uppercase?

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

Answers (3)

hwnd
hwnd

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

zx81
zx81

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

Fabricator
Fabricator

Reputation: 12772

like this? s/([a-z])\.([A-Z])/$1. $2/

Upvotes: 0

Related Questions