3

我需要从 Java 字符串标记器中获取子字符串。

我的输入字符串是 = Pizza-1*Nutella-20*Chicken-65*

        StringTokenizer productsTokenizer = new StringTokenizer("Pizza-1*Nutella-20*Chicken-65*", "*");
        do
        {
            try
            {
                int pos = productsTokenizer .nextToken().indexOf("-");
                String product = productsTokenizer .nextToken().substring(0, pos+1);
                String count= productsTokenizer .nextToken().substring(pos, pos+1);
                System.out.println(product + "   " + count);
            }
            catch(Exception e)
            {

            }
        }
        while(productsTokenizer .hasMoreTokens());

我的输出必须是:

Pizza  1
Nutella  20
Chicken  65

我需要单独变量中的产品值和计数值才能将该值插入数据库中。

我希望你能帮助我。

4

4 回答 4

3

You could use String.split() as

String[] products = "Pizza-1*Nutella-20*Chicken-65*".split("\\*");

for (String product : products) {
    String[] prodNameCount = product.split("\\-");
    System.out.println(prodNameCount[0] + " " + prodNameCount[1]);
}

Output

Pizza  1
Nutella  20
Chicken  65
于 2013-06-18T21:12:37.857 回答
0

如果您的输入增加,您可能想要使用的替代答案:

// find all strings that match START or '*' followed by the name (matched),
// a hyphen and then a positive number (not starting with 0)
Pattern p = Pattern.compile("(?:^|[*])(\\w+)-([1-9]\\d*)");
Matcher finder = p.matcher(products);
while (finder.find()) {
    // possibly check if the new match directly follows the previous one
    String product = finder.group(1);
    int count = Integer.valueOf(finder.group(2));
    System.out.printf("Product: %s , count %d%n", product, count);
}
于 2013-06-18T21:45:16.990 回答
0

您调用 nextToken() 方法 3 次。这将为您提供 3 个不同的令牌

int pos = productsTokenizer .nextToken().indexOf("-");
String product = productsTokenizer .nextToken().substring(0, pos+1);
String count= productsTokenizer .nextToken().substring(pos, pos+1);

相反,您应该执行以下操作:

String token = productsTokenizer .nextToken();
int pos = token.indexOf("-");
String product = token.substring(...);
String count= token.substring(...);

我会让你找出 substring() 方法的正确索引。

另外,不要使用 do/while 结构,最好只使用 while 循环:

while(productsTokenizer .hasMoreTokens())
{
    // add your code here
}   

那就是不要假设有一个令牌。

于 2013-06-18T21:28:59.813 回答
0

有些人不喜欢正则表达式,但这对他们来说是一个很好的应用程序。您需要使用的只是"(\\w+)-(\\d{1,})\\*"作为您的模式。这是一个玩具示例:

    String template = "Pizza-1*Nutella-20*Chicken-65*";
    String pattern = "(\\w+)-(\\d+)\\*";

    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(template);

    while(m.find())
    {
        System.out.println(m.group(1) + " " + m.group(2)); 
    }

为了更详细地解释这一点,"(\\w+)-(\\d+)\\*"查找 a (\\w+),它是任何一组至少 1 个字符 from [A-Za-z0-9_],后跟 a -,后跟一个 number \\d+,其中+表示长度至少为一个字符,后跟 a *,必须对其进行转义。括号捕获其中的内容。在这个正则表达式中有两组捕获括号,所以我们通过group(1)和引用它们,如循环group(2)中所见,它打印:while

Pizza 1
Nutella 20
Chicken 65
于 2013-06-18T21:51:00.693 回答