简体   繁体   中英

Text in between two specific words java

How can i get sting text in between "Thank" and "Sincerely,"

String emailtext= "Dear (RECIPIENT_PREFIX) (RECIPIENT_FIRST_NAME) (RECIPIENT_LAST_NAME), 
Thank you for being a part.....................more text ......

Thank you for your time. Filling out these sections with ...more     text....      for which you are chosen.

Sincerely,

xyz
adresss"

I tried:

String pattern = "(Thank)((.|\n)*)(?=Sincerely,)";

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(emailtext);

if (m.find( )) {
    System.out.println("Found value:" + m.group(0));
    System.out.println("Found value:" + m.group(1));
    System.out.println("Found value:" + m.group(2));
} else {
    System.out.println("NO MATCH");
}

error shows:

java.lang.StackOverflowError at java.util.regex.Pattern$CharProperty.match(Pattern.java:3692) at java.util.regex.Pattern$Branch.match(Pattern.java:4502) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4556) at java.util.regex.Pattern$Loop.match(Pattern.java:4683) at java.util.regex.Pattern$GroupTail.match(Pattern.java:4615) at java.util.regex.Pattern$BranchConn.match(Pattern.java:4466) at java.util.regex.Pattern$CharProperty.match(Pattern.java:3694) at java.util.regex.Pattern$Branch.match(Pattern.java:4502) at java.util.regex.Pattern$GroupHead.match(Pattern.java:4556) at java.util.regex.Pattern$Loop.match(Pattern.java:4683)

Correct ans should show :

"Thank you for being a part.....................more text ......

Thank you for your time. Filling out these sections with ...more text.... for which you are chosen."

give this a try:

String pattern = "(Thank)(.*)(?=Sincerely,)";

Pattern p = Pattern.compile(pattern,Pattern.DOTALL );
....

Well so you should check that both of the words are present in the text with

CharSequence s1 = "Thank";
CharSequence s2 = "Sincerely";
If (emailtext.contains(s1) && emailtext.contains(s2))

So that it can't throw an exception of that kind, then, you can just do:

String s = emailtext.substring(emailtext.lastIndexOf("Thank"),
  emailtext.indexOf("Sincerely"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM