使用正则表达式将字符串拆分为多个子字符串。应返回匹配和不匹配

时间:2013-10-28 12:50:48

标签: java regex

我想将一个字符串拆分成几个子字符串,我认为使用正则表达式可以帮助我。

I want this:        To become this:
<choice1>           {<choice1>}
c<hoi>ce2           {c, <hoi>, ce2}
<ch><oi><ce>3       {<ch>, <oi>, <ce>, 3}
choice4             {choice4}

请注意,大括号和逗号只是一个视觉辅助。最终形式是什么并不重要,只是值可以单独访问/替换。

提前致谢。

2 个答案:

答案 0 :(得分:4)

此代码应该有效:

String str = "<ch><oi><ce>3";
Pattern p = Pattern.compile("<[^>]*>|\\w+");
Matcher m = p.matcher(str);
while(m.find())
    System.out.printf("=> %s%n", m.group());

<强>输出:

=> <ch>
=> <oi>
=> <ce>
=> 3

答案 1 :(得分:3)

分裂

input.split("(?<!^)(?=<)|(?<=>)(?!$)");

虽然我会匹配他们

Matcher m=Pattern.compile("<[^>]*>|[^<>]+").matcher(input);
while(m.find())
{
     m.group();//matched value
}