java中的字符串解析

Geo*_*eos 4 java string parsing

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

this is a good example with 234 songs
this is %%type%% example with %%number%% songs
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢

Han*_*s W 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);
                }
        }
}
Run Code Online (Sandbox Code Playgroud)