I'm new to regular expressions and java so please bear with my newbish question.
I want to do the following:
If I have a string:
"I like ice cream only if it is chocolate ice cream. Chocolate cream"
and a pattern like
"chocolate ice cream"
I want to match and replace all words matched with a # surrounding them. Like this:
"I like #ice cream# only if it is #chocolate ice cream#. #Cholcolate cream#"
I used java's regex api and I understand I can use Matcher.replaceAll
. But I'm having trouble coming up with a proper regex. I came up with this chocolate*\\s*ice*\\s*cream*
. But the problem here is it's only matching the whole substring, i.e "chocolate ice cream"
. I think something like this could work:
chocolate|ice|cream|chocolate ice|ice cream|chocolate cream|chocolate ice cream
etc, i.e all permutations, but this would be cumbersome as the substring grows.
I would appreciate any ideas on proceeding in the right dire开发者_JAVA技巧ction.
Use the pattern:
(?i)\b((?:chocolate|ice|cream)(?:\s+(?:chocolate|ice|cream))*)\b
and replace it with:
#$1#
Demo:
String s = "I like ice cream only if it is chocolate ice cream. Chocolate cream";
s = s.replaceAll("(?i)\\b((?:chocolate|ice|cream)(?:\\s+(?:chocolate|ice|cream))*)\\b", "#$1#");
System.out.println(s);
The word boundaries cause "creamy" (and other such words) not to be replaced.
Note that this will change "ice ice"
into "#ice ice#"
(ie. the words can occur more than once!), as @stema mentioned in the comments.
(?:chocolate|ice|cream)(?:\s+(?:chocolate|ice|cream))*
This will match one or more of the specified words delimited by whitespace
Try this:
final String source = "I like ice cream only if it is chocolate ice cream. Chocolate cream";
final String result = source.replaceAll("((?:[Cc]hocolate )?(?:[Ii]ce )?cream)", "#$1#");
// Prints I like #ice cream# only if it is #chocolate ice cream#. #Chocolate cream#
System.out.println(result);
See Optional Items for more information.
Maybe you will find interesting MessageFormat from the Java API
Object[] testArgs = {new Long(3), "MyDisk"};
MessageFormat form = new MessageFormat(
"The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
// output, with different testArgs
output: The disk "MyDisk" contains 0 file(s).
output: The disk "MyDisk" contains 1 file(s).
output: The disk "MyDisk" contains 1,273 file(s).
精彩评论