Search code examples
regexstringreplaceall

ReplaceAll with regex is removing one extra char which dont want to in Java


I have a text as below

blah blah blah test.this@gmail.com blah blah  
blah blah blah jjathis.this @gmail.com blah blah  
blah blah blah this.this.this@gmail.com blah blah this 

I want to replace all "this" word with "that" word except the "this" starts with ".". So here ".this" should not get replaced everything else should get replaced. I have written below code.

replaceAll("[^\\.]"+"this", "that")  

This is not replacing .this but the problem is it is considering one extra char before the string. Ex: jjathis is coming like jjthat. but it should be jjathat.
Why replaceall is changing the one more extra char at start? What should be the solution?
Please help.


Solution

  • Maybe,

    (?<!\\.)this
    

    replaced with

    that
    

    might work OK.

    Test

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    
    public class RegularExpression{
    
        public static void main(String[] args){
    
            final String regex = "(?<!\\.)this";
            final String string = "blah blah blah test.this@gmail.com blah blah  \n"
                 + "blah blah blah jjathis.this @gmail.com blah blah  \n"
                 + "blah blah blah this.this.this@gmail.com blah blah this ";
            final String subst = "that";
    
            final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
            final Matcher matcher = pattern.matcher(string);
    
            final String result = matcher.replaceAll(subst);
    
            System.out.println(result);
    
        }
    }
    

    Output

    blah blah blah test.this@gmail.com blah blah  
    blah blah blah jjathat.this @gmail.com blah blah  
    blah blah blah that.this.this@gmail.com blah blah that 
    

    If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.