【问题标题】:Extract string between by [" "] [duplicate]在 [" "] [重复] 之间提取字符串
【发布时间】:2017-06-06 20:01:46
【问题描述】:

如何在[" "] 之间提取字符串 我有例如:["x"],那么我怎样才能只提取x 并将其分配给 多变的 我试过这个:

String str = "[x]";    
String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));

我可以使用上面的代码得到 x,但我的字符串包含在 [" "] 之间

【问题讨论】:

  • 您需要使用正则表达式还是可以将 [" 和 "] 替换为 ""
  • @farrellmr 字符串在[" "] 之间,而不仅仅是" "
  • 我的意思是空字符串 "[x]".replace("[", "").replace("]", "");产生 x

标签: java regex string jmeter


【解决方案1】:

最简单的方法如下:

String s = "aaaa [\"axas\"]";
String result = s.substring(s.indexOf("[\"")+2, s.indexOf("\"]"));

\" 代表一个字符 " - \ 是一个转义字符,它是您的解决方案中缺少的部分。

结果:

【讨论】:

  • 您的代码运行良好。但在我的情况下,x 是一个 json 对象,我使用 jmeter 中的 json 路径提取器提取它,提取时的结果是 name=["x"]。那么我如何附加那些/,因为我在提取时得到的结果是这种模式["x"] only
【解决方案2】:

这个正则表达式似乎有效:

final String regexpStr = "\\[\"(.*?)\"\\]";

JUnit 测试:

@Test
public void regexp() {
    final String[] noMatch = { "", "[", "[\"", "]", "\"]", "\"[", "]\"", "asdf",
            "[\"asdfasdf\"", "asdf[sadf\"asdf\"]" };
    final String[] match = { "[\"one\"]", "asdf[\"one\"]", "[\"one\"]asdf", "asdf[\"one\"]asdf",
            "asdf[\"one\"]asdf[\"two\"]asdf" };
    final String regexpStr = "\\[\"(.*?)\"\\]";

    final Pattern pattern = Pattern.compile(regexpStr);
    for (final String s : noMatch) {
        final Matcher m = pattern.matcher(s);
        Assert.assertFalse(m.matches());
    }

    for (final String s : match) {
        final Matcher m = pattern.matcher(s);
        Assert.assertTrue(m.find());
        Assert.assertEquals(m.group(1), "one");
        if (m.find()) {
            Assert.assertEquals(m.group(1), "two");
        }
    }
}

【讨论】:

    【解决方案3】:
    package soquestion;
    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class SOQuestion {
    
        public static void main(String[] args) {
            String str = "[\"foo\"] and [\"bar\"]";
            System.out.println("String is: " + str);
            Pattern p = Pattern.compile("\\[\\\"(.*?)\\\"\\]");
            Matcher m = p.matcher(str);
            while (m.find()) {
                System.out.println("Result: " + m.group(1));
            }            
        }
    
    }
    

    结果:

    String is: ["foo"] and ["bar"]
    Result: foo
    Result: bar
    

    【讨论】:

      【解决方案4】:

      使用以下代码:

      public static void main(final String[] args) {
          String in = "[ABC]";
      
          Pattern p = Pattern.compile("\\[(.*)\\]");
          Matcher m = p.matcher(in);
      
          while(m.find()) {
              System.out.println(m.group(1));
          }
      }
      

      【讨论】:

      • 对不起。它是括号内的引号。你反其道而行之。 :)
      猜你喜欢
      • 1970-01-01
      • 2019-10-13
      • 1970-01-01
      • 2018-05-11
      • 2018-07-26
      • 1970-01-01
      • 2012-11-27
      • 2016-12-09
      • 2021-02-21
      相关资源
      最近更新 更多