如何在 Java 中将一个字符串拆分为 2 个字符串

How to split a string by 2 strings in Java

如何将这个字符串分成两个词?

<input type="hidden" name="SYNCHRONIZER_TOKEN" value="2f56248e-e54d-48ef-8c8c-6028d6f3d63f" id="SYNCHRONIZER_TOKEN" />

字符串 1:value="

字符串 2:" id="SYNC

每次拆分后字符串需要如下所示:2f56248e-e54d-48ef-8c8c-6028d6f3d63f

尝试使用正则表达式提取感兴趣的值。这样你的代码就不会做任何假设,如果 value=...

之后有完全不同的东西也不会中断
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SplitString {
    public static void main(String[] args){
        String input = "<input type=\"hidden\" name=\"SYNCHRONIZER_TOKEN\" value=\"2f56248e-e54d-48ef-8c8c-6028d6f3d63f\" id=\"SYNCHRONIZER_TOKEN\" />\n";
        Pattern pattern = Pattern.compile("value=\"[a-zA-Z0-9-]+\"");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()){
            String keyValue = matcher.group(0);
            String key = keyValue.split("=")[0];
            String value = keyValue.split("=")[1];
            System.out.println("KeyValue: " + keyValue);
            System.out.println("Key: " + key);
            System.out.println("Value: " + value);
        }
    }
}

输出看起来像这样

KeyValue: value="2f56248e-e54d-48ef-8c8c-6028d6f3d63f"
Key: value
Value: "2f56248e-e54d-48ef-8c8c-6028d6f3d63f"