【问题标题】:string parsing in javajava中的字符串解析
【发布时间】:2011-01-16 17:51:42
【问题描述】:

在 Java 中执行以下操作的最佳方法是什么。 我有两个输入字符串

this is a good example with 234 songs
this is %%type%% example with %%number%% songs

我需要从字符串中提取类型和数字。

在这种情况下,答案是 type="a good" and number="234"

谢谢

【问题讨论】:

  • 我不明白你在做什么??您是否尝试提取“this is”和“example”之间的值?

标签: java string parsing


【解决方案1】:

地理位置, 我建议使用 Apache Velocity 库 http://velocity.apache.org/。它是一个字符串模板引擎。你的例子看起来像

this is a good example with 234 songs
this is $type example with $number songs

执行此操作的代码如下所示

final Map<String,Object> data = new HashMap<String,Object>();
data.put("type","a good");
data.put("number",234);

final VelocityContext ctx = new VelocityContext(data);

final StringWriter writer = new StringWriter();
engine.evaluate(ctx, writer, "Example templating", "this is $type example with $number songs");

writer.toString();

【讨论】:

  • 我认为他正在尝试做模板的“反面”。 IE。给定输出字符串和模板提取生成输出的上下文。
【解决方案2】:

Java has regular expressions:

Pattern p = Pattern.compile("this is (.+?) example with (\\d+) songs");
Matcher m = p.matcher("this is a good example with 234 songs");
boolean b = m.matches();

【讨论】:

    【解决方案3】:

    如果第二个字符串是一个模式。你可以把它编译成正则表达式,就像一个

    String in = "this is a good example with 234 songs";
    String pattern = "this is %%type%% example with %%number%% songs";
    Pattern p = Pattern.compile(pattern.replaceAll("%%(\w+)%%", "(\\w+)");
    Matcher m = p.matcher(in);
    if (m.matches()) {
       for (int i = 0; i < m.groupsCount(); i++) {
          System.out.println(m.group(i+1))
       }
    }
    

    如果您需要命名组,您还可以解析字符串模式并将组索引和名称之间的映射存储到某个 Map 中

    【讨论】:

      【解决方案4】:

      你可以用正则表达式来做到这一点:

      import java.util.regex.*;
      
      class A {
              public static void main(String[] args) {
                      String s = "this is a good example with 234 songs";
      
      
                      Pattern p = Pattern.compile("this is a (.*?) example with (\\d+) songs");
                      Matcher m = p.matcher(s);
                      if (m.matches()) {
                              String kind = m.group(1);
                              String nbr = m.group(2);
      
                              System.out.println("kind: " + kind + " nbr: " + nbr);
                      }
              }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-30
        • 1970-01-01
        • 1970-01-01
        • 2012-08-06
        • 2014-10-19
        • 1970-01-01
        相关资源
        最近更新 更多