Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a java regular expression pattern that would match a string only at certain positon?

Tags:

java

regex

I would like to create a regular expression pattern that would succeed in matching only if the pattern string not followed by any other string in the test string or input string ! Here is what i tried :

      Pattern p = Pattern.compile("google.com");//I want to know the right format

      String input1 = "mail.google.com";
      String input2 = "mail.google.com.co.uk";

      Matcher m1 = p.matcher(input1);
      Matcher m2 = p.matcher(input2);

      boolean found1 = m1.find();
      boolean found2 = m2.find();//This should be false because "google.com" is followed by ".co.uk" in input2 string

Any help would be appreciated!

like image 472
Xris Avatar asked Apr 14 '26 06:04

Xris


2 Answers

Your pattern should be google\.com$. The $ character matches the end of a line. Read about regex boundary matchers for details.

like image 102
Mansoor Siddiqui Avatar answered Apr 15 '26 19:04

Mansoor Siddiqui


Here is how to match and get the non-matching part as well.

Here is the raw regex pattern as an interactive link to a great regular expression tool

^(.*)google\.com$

^ - match beginning of string
(.*) - capture everything in a group up to the next match
google - matches google literal
\. - matches the . literal has to be escaped with \
com - matches com literal
$ - matches end of string

Note: In Java the \ in the String literal has to be escaped as well! ^(.*)google\\.com$


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!