简体   繁体   中英

How to extract content between two words in a text file using Java?

I have a text file and I want to extract the content between these two words using Java .

I am new to Java ,can anyone help me out ?

This is the method in R language to extract content between words Directions & Ingredients .

   sub("."*Directions*(.*?)* Photograph.*,\\1",x)

where x is the text content . Can anyone tell me the corresponding code in Java .

Thanks

Use Java Pattern class:

String x = new String("string that contains Directions and Photograph. ");
Pattern pattern = Pattern.compile("Directions(.*?) Photograph");
Matcher matcher = pattern.matcher(x); 
while (matcher.find()) {
System.out.println(matcher.group(1));
}

Live DEMO

If you are allowed to use apache-commons ; this can be elegantly done as :

String[] results =  StringUtils.substringsBetween(str,"Directions","Photograph");

Where str being the string in question. Dependency you need is commons-lang-XXX.jar

Thes simplest way is:

    String originalString = "bla, bla, bla, Directions bla ... bla ... bla.... Ingredients ....";
    String result = originalString.substring(originalString.indexOf("Directions")+"Directions".length(), originalString.indexOf("Ingredients"));
    System.out.println(result);

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