0

For example I have this text and email:

String text ="For move information please contact us: contact@gmail.com, ask Peter to help."
String email="contact@gmail.com";

I want to get two 10 chars sized strings as a result, one from the left side of email, other from the right. Result I want to see: Left-ntact us: Right:, ask Pete

Right now matcher.find() in while loop returns false. And as a result both leftContext and rightContext are null.

Here is my code:

String email = "contact@gmail.com";
int nLeft = 5;
int nRight = 5;
String leftContext;
String rightContext;

String wordDelRegEx = "[^а-яА-Яa-zA-Z0-9.-]+?";
        String leftRegEx = "(\\w{" + nLeft + "})";
        String rightRegEx = "(\\w{" + nRight + "})";

        //matches something like: aaaaaaa email@gmail.com bbbbbbbbbb
        String contextRe = leftRegEx + wordDelRegEx +email + wordDelRegEx + rightRegEx;

        String h ="For move information please contact us: contact@gmail.com, ask Peter to help."
        Pattern pattern = Pattern.compile(contextRe);
        Matcher matcher = pattern.matcher(h);

        while (matcher.find()) {
            leftContext = matcher.group(1);
            rightContext = matcher.group(2);
        }

        System.out.println("Left: " + leftContext);
        System.out.println("Right: " + rightContext);
Steve
  • 415
  • 2
  • 8
  • 24
  • It fails in this particular case because you're searching for "email@gmail.com" but your sample string has "contact@gmail.com". – user1676075 Sep 02 '14 at 20:11
  • Sorry, my fault. It is not the reason, I edited question. – Steve Sep 02 '14 at 20:20
  • Also, your question has examples where you want space and `:` in the result, but your `leftRegEx` and `rightRegEx` patterns won't allow that because space and `:` won't match `\\w`. – ajb Sep 02 '14 at 20:21
  • Additionaly, you have to escape the `.` in `èmail`. See http://stackoverflow.com/questions/14134558/java-regex-list-of-all-special-characters-that-needs-to-be-escaped-in-regex – Smutje Sep 02 '14 at 20:22
  • I tried to change it, but no effect: String leftRegEx = "(.{" + nLeft + "})"; String rightRegEx = "(.{" + nRight + "})"; – Steve Sep 02 '14 at 20:23
  • @Smutje, I tried email = "support@dou\\Q.\\Eua"; still nothing – Steve Sep 02 '14 at 20:43

1 Answers1

0

Use following as your string contains colon (:), comma(,) and spaces (\s):

There is no Use of wordDelRegEx variable:

String leftRegEx = "([\\w\\s,:]{" + nLeft + "})";

String rightRegEx = "([\\w\\s,:]{" + nRight + "})";

//matches something like: aaaaaaa email@gmail.com bbbbbbbbbb

String contextRe =leftRegEx+ email +rightRegEx;
Hansraj
  • 174
  • 5