javaregexmatch

How to match specific character after another specific character


I need to find a specific character after another specific character. For example

jhony@domain.com

I need to find the first occurrence of "." until the end of word after the first occurrence of "@"

I tried this pattern but I was not successful:

(?<=@)([.])$

https://regex101.com/r/sTRpxp/1


Solution

  • Alternative regex:

    "(?<=@\\w{1,100})(\\.\\S+)"
    

    Regex in context and testbench:

    public static void main(String[] args) {
        String input = "jhony@domain.com";
    
        Pattern pattern = Pattern.compile("(?<=@\\w{1,100})(\\.\\S+)");
        Matcher matcher = pattern.matcher(input);
        if(matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
    

    Matching without "group number":

    public static void main(String[] args) {
        String input = "jhony@domain.com";
    
        Pattern pattern = Pattern.compile("(?<=@\\w{1,100})\\.\\S+");
        Matcher matcher = pattern.matcher(input);
        if(matcher.find()) {
            System.out.println(matcher.group());
        }
    }
    

    Output:

    .com
    

    More about Pattern's 'Special constructs' can be found here: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html