Diwas
Diwas

Reputation: 33

extract a set of a characters between some characters

I have a string email = [email protected]

How can I write a java code using regex to bring just the r2d2? I used this but got an error on eclipse

String email = [email protected]
Pattern pattern = Pattern.compile(".(.*)\@");
Matcher matcher = patter.matcher      
for (Strimatcher.find()){
   System.out.println(matcher.group(1));
} 

Upvotes: 0

Views: 76

Answers (3)

Youcef LAIDANI
Youcef LAIDANI

Reputation: 60026

No need to Pattern you just need replaceAll with this regex .*\.([^\.]+)@.* which mean get the group ([^\.]+) (match one or more character except a dot) which is between dot \. and @

email = email.replaceAll(".*\\.([^\\.]+)@.*", "$1");

Output

r2d2

regex demo


If you want to go with Pattern then you have to use this regex \\.([^\\.]+)@ :

String email = "[email protected]";
Pattern pattern = Pattern.compile("\\.([^\\.]+)@");
Matcher matcher = pattern.matcher(email);
if (matcher.find()) {
    System.out.println(matcher.group(1));// Output : r2d2
}

Another solution you can use split :

String[] split = email.replaceAll("@.*", "").split("\\.");
email = split[split.length - 1];// Output : r2d2

Note :

  • Strings in java should be between double quotes "[email protected]"
  • You don't need to escape @ in Java, but you have to escape the dot with double slash \\.
  • There are no syntax for a for loop like you do for (Strimatcher.find()){, maybe you mean while

Upvotes: 0

Thatalent
Thatalent

Reputation: 424

Not sure if your posting the right code. I'll rewrite it based on what it should look like though:

    String email = [email protected]
    Pattern pattern = Pattern.compile(".(.*)\@");
    Matcher matcher = pattern.matcher(email);
    int count = 0;
    while(matcher.find()) {
       count++;
       System.out.println(matcher.group(count));
   } 

but I think you just want something like this:

String email = [email protected]
Pattern pattern = Pattern.compile(".(.*)\@");
Matcher matcher = pattern.matcher(email);
if(matcher.find()){
       System.out.println(matcher.group(1));
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

To match after the last dot in a potential sequence of multiple dots request that the sequence that you capture does not contain a dot:

(?<=[.])([^.]*)(?=@)
  • (?<=[.]) means "preceded by a single dot"
  • (?=@) means "followed by @ sign"

Note that since dot . is a metacharacter, it needs to be escaped either with \ (doubled for Java string literal) or with square brackets around it.

Demo.

Upvotes: 1

Related Questions