【问题标题】:java How to get the list from a string by the specified symbol?java如何通过指定符号从字符串中获取列表?
【发布时间】:2014-04-28 04:08:55
【问题描述】:

例如我有一个字符串

"123<a>3213<b>3434343<c>,example <d><1><2><3>"

我想通过符号"<>"获取内文

如何获取列表[a,b,c,d,1,2,3]???

【问题讨论】:

  • 你想要得到的字符有什么特别之处?
  • 您可以使用某种特殊的堆栈实现。类似于如果您尝试像编译器一样验证打开关闭 {}s 或 ()s。
  • 您尝试过任何正则表达式和/或模式匹配吗?
  • 所以你可以和他们一起练习,这样他们就不会那么难了。作为程序员,它们非常有用,无论如何你都应该熟悉它们。
  • 不要放弃。 Here 是 Java 正则表达式的教程。 HerePattern 的 javadoc。

标签: java string substring


【解决方案1】:

您可以使用StringUtils.substringsBetween(String str, String open, String close)

String[] parts = StringUtils.substringsBetween("123<a>3213<b>3434343<c>,example <d><1><2><3>", "<", ">");

【讨论】:

    【解决方案2】:

    您想要&lt;..&gt; 之间的文本。在给定的String 上使用PatternMatcher,同时对&lt;..&gt; 之间的文本进行分组

    String text = "123<a>3213<b>3434343<c>,example <d><1><2><3>";
    Pattern pattern = Pattern.compile("<(.*?)>"); // reluctant quantifier
    Matcher matcher = pattern.matcher(text);
    List<String> entries = new LinkedList<>();
    while (matcher.find()) 
        entries.add(matcher.group(1)); // group 0 is the whole match, we only want what's between <>
    System.out.println(entries);
    

    打印出来

    [a, b, c, d, 1, 2, 3]
    

    【讨论】:

      【解决方案3】:

      未经测试,几乎没有防弹,几乎没有错误检查,但它应该可以工作。当然事情可能会更好,这只是凭记忆。

      public List<String> getThings(String source) {
          char[] chars = source.toCharArray();
          boolean capturing = false;
          List<String> result = new ArrayList<String>();
          String token = "";
      
          for(char c : chars) {
              if (!capturing) {
                  if (c == '<') { // found open delimiter, start capture.
                      capturing = true;
                      continue;
                  }
              } else {
                  if (c == '>') { // Found closing delimiter, stop capture.
                      results.add(token);
                      token = "";
                      capturing = false;
                      continue;
                  }
                  token = token + c;
              }
          }
          if (!scanning) {
              throw new RuntimeException("Source string ended with missing closing '>'");
          }
          return results;
      }
      

      【讨论】:

        猜你喜欢
        • 2015-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-03
        • 1970-01-01
        • 2012-01-12
        相关资源
        最近更新 更多