You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中提取指定字符串后双引号内的内容求助

提取字符串中text2后双引号内的内容(Java实现)

针对你给出的字符串,这里有两种简单易懂的实现方法,适合Java新手:

方法一:使用正则表达式(推荐,适配类似格式的键值对)

正则可以精准匹配text2="xxx"这种格式,直接捕获引号内的内容:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String myString = "text1=\"value1\" text2=\"value2\" text3=\"value3\"";
        // 正则规则:匹配text2=",然后捕获所有非引号的内容
        Pattern pattern = Pattern.compile("text2=\"([^\"]+)\"");
        Matcher matcher = pattern.matcher(myString);
        
        if (matcher.find()) {
            String result = matcher.group(1); // 取第一个分组的内容
            System.out.println(result); // 输出:value2
        }
    }
}

解释:([^"]+)表示捕获所有不是双引号的字符,刚好对应引号里的内容,不会匹配到后面的其他引号。

方法二:字符串截取(步骤清晰,适合理解基础操作)

通过定位关键位置,一步步截取目标内容:

public class Main {
    public static void main(String[] args) {
        String myString = "text1=\"value1\" text2=\"value2\" text3=\"value3\"";
        // 找到text2="的起始位置
        int startMarker = myString.indexOf("text2=\"");
        if (startMarker != -1) {
            // 跳过text2=",定位到引号内内容的起始位置
            int startIndex = startMarker + "text2=\"".length();
            // 找到下一个双引号的位置
            int endIndex = myString.indexOf("\"", startIndex);
            if (endIndex != -1) {
                String result = myString.substring(startIndex, endIndex);
                System.out.println(result); // 输出:value2
            }
        }
    }
}

解释:先找到text2=\"的位置,然后往后偏移长度找到内容开头,再找后面第一个引号的位置,中间的子串就是目标值。

内容的提问来源于stack exchange,提问作者Neha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 18:22:10