-1

I am trying to extract a certain portion of string from a main string. For example, I have the following string.

A receipt is sent to abc@gmail.com. Please keep it for your own reference.

I just want to extract

abc@gmail.com

from the string.

From the solutions I found, it utlises the "count" of index from beginning of the String up to the beginning of the email section of the string, and from after the email section to the end of the string. However, I think this only works if the number of characters in the email is fixed. Unfortunately, mine here is dynamic, which means the string remains the same except that the email will be populated with the email that the user keyed in. Kindly advise.

1 Answers1

1

Assuming you are starting with this input string and just want to extract a single email address, you may consider using String#replaceAll for a one-liner option:

String input = "A receipt is sent to abc@gmail.com. Please keep it for your own reference.";
String email = input.replaceAll(".*\\b(\\w\\S*@\\S*\\w)\\b.*", "$1");
System.out.println(email);

This prints:

abc@gmail.com
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thanks, Tim ! It did the trick ! Mind sharing briefly what just happened ? I mean, other solutions were quite complicated which involves deriving patterns and all, but yours were much simpler. – Tester_at_work Aug 06 '20 at 04:57
  • The problem with using a positional approach is that, without regex, it is difficult to articulate where an email address should begin and where it should end. – Tim Biegeleisen Aug 06 '20 at 05:23