Phoenix
Phoenix

Reputation: 8933

Replacing all occurrences of a word with another

I'm writing a regex to match every occurrence of "japan" and replace it with "Japan" .. why doesn't the below work ? And "japan" can occur multiple times in a sentence and anywhere in a sentence. I want to replace all occurrences

public static void testRegex()
{
    String input = "The nonprofit civic organization shall comply with all other requirements of section 561.422, japan laws, in obtaining the temporary permits authorized by this act.";
    String regex = "japan";
    Pattern p = Pattern.compile(regex);
    Matcher m = p.matcher(input);
    System.out.println(input.matches(regex));
    System.out.println(input.replaceAll(regex, "Japan"));

}

Upvotes: 0

Views: 149

Answers (3)

sp00m
sp00m

Reputation: 48837

input.matches(regex) auto-anchors your pattern with ^ and $. Simply surround your pattern with .* to have matches.

But then, the replaceAll won't work anymore. Thus, you'll have to replace (.*?)japan(.*?) by $1Japan$2.

Upvotes: 0

Reimeus
Reimeus

Reputation: 159874

replaceAll is working as intended.

From your comment:

The regex match evaluates to false.

This statement evaluates to false

System.out.println(input.matches(regex));

as String#matches matches the complete String. Since the String "japan" is not a regex, you could do

System.out.println(input.contains(regex));

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213411

You don't need regex here, and neither Pattern and Matcher classes. Simple use of String.replace() will work fine:

input = input.replace("japan", "Japan");

Upvotes: 7

Related Questions