Reputation: 33
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
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
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 :
"[email protected]"
@
in Java, but you have to escape the dot with double slash \\.
for (Strimatcher.find()){
, maybe you mean while
Upvotes: 0
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
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.
Upvotes: 1