[Java] How to extract a string between two delimiters

Posted in :

取字串中間的值,每個程式語言必然會遇到。Java 的解法:

If you have just a pair of brackets ( [] ) in your string, you can use indexOf():

String str = "ABC[ This is the text to be extracted ]";    
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

import java.util.Date;
import org.apache.commons.lang.StringUtils;
 
public class Main {
    public static void main(String[] args) {
        String helloHtml = "<html>" +
                "<head>" +
                "   <title>Hello World from Java</title>" +
                "<body>" +
                "Hello, today is: " + new Date() +
                "</body>" +
                "</html>";
        
        String title = StringUtils.substringBetween(helloHtml, "<title>", "</title>");
        String content = StringUtils.substringBetween(helloHtml, "<body>", "</body>");
        
        System.out.println("title = " + title);
        System.out.println("content = " + content);
    }
}

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>");
String[] result = pattern.split(str);
System.out.println(Arrays.toString(result));

it return

[ZZZZL ,  AFFF ]

But my expectation is:

[ dsn , AFG ]

 

Your pattern is fine. But you shouldn’t be split()ting it away, you should find() it. Following code gives the output you are looking for:

String str = "ZZZZL <%= dsn %> AFFF <%= AFG %>";
Pattern pattern = Pattern.compile("<%=(.*?)%>");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

這個 sample 滿好的,需要 import 到 2 個 Class,

java.util.regex.Pattern

java.util.regex.Matcher

需要 debug 的話,可以 output matcher.group(0) ,差異在包在括號外面的常數,要不要一起顯示, (1) 是只取出括號裡的變數,(0) 是包含外面常數。

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *