【问题标题】:Get the value after a string and comma and ends if there is character '|'获取字符串和逗号后的值,如果有字符'|'则结束
【发布时间】:2019-12-05 10:29:06
【问题描述】:

如果我有字符串变量:

String word = "wordA";

我还有另一个字符串变量:

String fullText= "wordA,A A|wordB,B B|wordC,C C|wordD,D D";

那么是否有可能获取逗号后并以|结尾的值?

示例

如果 word 等于 "wordA",那么我只会得到 "A A",因为在全文中 wordA 和逗号之后是“A A”并以 | 结尾

如果 word 等于 "wordD",则基于变量 fullText 的变量结果为 "D D"

那么如何在 Java 中得到这个变量结果呢?

【问题讨论】:

  • 请给我们您当前的解决方案草图!
  • 查看带有捕获组的正则表达式。
  • 我尝试了几种方法,但仍然卡住。我已经尝试了所有字符串操作,但找不到获得预期值的正确方法。另外,如果我知道答案,我不会问顺便说一句。谢谢你的回答

标签: java arrays string algorithm


【解决方案1】:

您可以使用简单的正则表达式。像这样:

String text = fullText.replaceAll(".*" + word + ",([^\\|]+).*", "$1");

或者:

Matcher matcher = Pattern.compile(word + ",([^\\|]+)").matcher(fullText);
matcher.find();
matcher.group(1); // "A A" for word = wordA

【讨论】:

    【解决方案2】:

    如果你使用的是 Java8,你可以像这样使用流:

    String result = Arrays.stream(fullText.split("\\|")) // split with |
            .filter(s -> s.startsWith(word + ","))       // filter by start with word + ','
            .findFirst()                                 // find first or any
            .map(a -> a.substring(word.length() + 1))    // get every thing after work + ','
            .orElse(null);                               // or else null or any default value
    

    【讨论】:

    • 它有效,非常感谢您的回答。但是,如果我插入除该示例“worddd”之外的变量词的值,那么它将返回“A A”
    • @user_22 你说如果你通过了worddd,你会得到A A ??
    【解决方案3】:

    这个怎么样:

    public static String search(String fullText, String key) {
        Pattern re = Pattern.compile("(?:^|\\|)" + key + ",([^|]*)(?:$|\\|)");
        Matcher matcher = re.matcher(fullText);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }
    

    例子:

        String fullText= "wordA,A A|wordB,B B|wordC,C C|wordD,D D";
        System.out.println(search(fullText, "wordA"));
        System.out.println(search(fullText, "wordB"));
        System.out.println(search(fullText, "wordC"));
        System.out.println(search(fullText, "wordD"));
    

    输出:

    A A
    B B
    C C
    D D
    

    更新:为避免在每次搜索时重新编译正则表达式:

    private static final Pattern RE = Pattern.compile("(?:^|\\|)([^,]*),([^|]*)(?:$|(?=\\|))");
    
    public static String search(String fullText, String key) {
        Matcher matcher = RE.matcher(fullText);
        while (matcher.find()) {
            if (matcher.group(1).equals(key)) {
                return matcher.group(2);
            }
        }
        return null;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-31
      • 2021-01-31
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-03-17
      相关资源
      最近更新 更多