Reputation: 401
I have a String like
"This is apple tree"
I want to remove the white spaces available until the word apple.After the change it will be like
"Thisisapple tree"
I need to achieve this in single replace command combined with regular expressions.
Upvotes: 0
Views: 87
Reputation: 629
If you want to use a regular expression you could try:
Matcher matcher = Pattern.compile("^(.*?\\bapple\\b)(.*)$").matcher("This is an apple but this apple is an orange");
System.out.println((!matcher.matches()) ? "No match" : matcher.group(1).replaceAll(" ", "") + matcher.group(2));
This checks that "apple" is an individual word and not just part of another word such as "snapple". It also splits at the first use of "apple".
Upvotes: 0
Reputation: 124215
For now it looks like you may be looking for
String s = "This is apple tree";
System.out.println(s.replaceAll("\\G(\\S+)(?<!(?<!\\S)apple)\\s", "$1"));
Output: Thisisapple tree
.
Explanation:
\G
represents either end of previous match or start of input (^
) if there was no previous match yet (when we are attempting to find first match)\S+
represents one or more non-whitespace characters (to match words, including non-alphabetic characters like '
or punctuation)(?<!(?<!\\S)apple)\\s
negative-look-behind will prevent accepting whitespace which has apple
before it (I added another negative-look-behind before apple
to make sure that it doesn't have any non-whitespace which ensures that this is not part of some other word)$1
in replacement represents match from group 1 (the one from (\S+)
) which represents word. So we are replacing word and spaces with only word (effectively removing spaces)WARNING: This solution assumes that
If we want to get rid of this assumptions we would need something like:
System.out.println(s.replaceAll("^\\s+|\\G(\\S+)(?<!(?<!\\S)apple)\\s+", "$1"));
^\s+
will allow us to match spaces at beginning of string (and replace them with content of group 1 (word) which in this case will be empty, so we will simply remove these whitespaces)\s+
at the end allows us to match word and one or more spaces after it (to remove them)Upvotes: 1
Reputation: 3415
This is achived via lookahead assertion, like this:
String str = "This is an apple tree";
System.out.println(str.replaceAll(" (?=.*apple)", ""));
It means: replace all spaces in front of which there anywhere word apple
Upvotes: 0
Reputation: 1027
A single replace() is unlikely to solve your problem. You could do something like this..
String s[] = "This is an apple tree, not an orange tree".split("apple");
System.out.println(new StringBuilder(s[0].replace(" ","")).append("apple").append(s[1]));
Upvotes: 0