java中的字符串解析 [英] string parsing in java

查看:206
本文介绍了java中的字符串解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to do the following in Java. I have two input strings

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

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

I need to extract type and number from the string.

这种情况下的答案是type =a good和number =234

Answer in this case is type="a good" and number="234"

谢谢

推荐答案

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

You can do it with regular expressions:

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

这篇关于java中的字符串解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆