How to get a char sequence from String that contains a searched string

1.3k Views Asked by At

I would like to know if their is a function in JAVA that allows to retrieve from a huge string a char sequence that contains a special char.

Example: I have a php page that that I've stringified and I check if there is a char sequence containing the char "@". If it's the case, I would like to get just the whole char sequence that contains the searched char.

I can use String.contains("@") to look for the char but how to get the char which contains it ?

Thanks in advance !

3

There are 3 best solutions below

3
On BEST ANSWER

You can use a regular expression based on

"mailto = ([email protected])"

If this is found in the stringified php, you can conveniently extract the parenthesized section.

But most likely it could be [email protected] as well, and so you may have to write a more complicated regular expression, but it'll work the same way.

Here's a version matching any valid email address:

"mailto = ([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+(?:\\.[A-Za-z]){1,3}\\b)"

Perhaps the spaces before and after = aren't guaranteed, so you might make them optional:

"mailto ?= ?(...)"

To execute the match, use

Pattern pat = Pattern.compile( "mailto = ([A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+(?:\\.[A-Za-z]){1,3}\\b)" );

and, with the php in a String you can then do

String php = ...;
Matcher mat = pat.matcher( php );
if( mat.find() ){
    String email = mat.group( 1 );
}

The find can be called repeatedly to find all occurrences.

See another SO Q+A for the discussion of a regular expression matching an email address.

4
On

You could use a combination of indexOf and substring to find and extract the substring.

Without more info on how the source and the searched string look like it's hard to help you further.

0
On

Since the regex idea was already taken, here's another approach

String test = "abc 123 456@789 abcde";
String charToFind = "@";

String strings[] = test.split(" ");
for( String str : strings ){
  if( str.contains(charToFind) ){ System.out.println(str); }
}