5

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

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

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

提前致谢。

4

2 回答 2

4

This code should work:

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

OUTPUT:

=> <ch>
=> <oi>
=> <ce>
=> 3
于 2013-10-28T12:56:06.857 回答
3

带分体

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

虽然我会匹配他们

Matcher m=Pattern.compile("<[^>]*>|[^<>]+").matcher(input);
while(m.find())
{
     m.group();//matched value
}
于 2013-10-28T12:53:37.513 回答