Java中的字符串解析

4

在Java中,以下是最好的实现方式。我有两个输入字符串。

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

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

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

谢谢


我不明白你想做什么?你是想提取在“this is”和“example”之间的值吗? - curv
4个回答

7

您可以使用正则表达式来完成:

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);
                }
        }
}

3
Java拥有正则表达式:

Java正则表达式文档


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();

1
如果第二个字符串是一个模式,你可以将其编译成正则表达式,就像这样
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 中。

0

Geos, 我建议使用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();

我认为他试图做的是“反模板化”。也就是说,根据输出字符串和模板提取生成输出的上下文。 - flybywire

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接