0

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 !

Hubert Solecki
  • 2,611
  • 5
  • 31
  • 63

3 Answers3

2

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.

Community
  • 1
  • 1
laune
  • 31,114
  • 3
  • 29
  • 42
1

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); }
}
Gary
  • 13,303
  • 18
  • 49
  • 71
0

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.

wonderb0lt
  • 2,035
  • 1
  • 23
  • 37