Java - 由分隔符拆分

时间:2012-04-13 06:33:11

标签: java regex split

鉴于_<A_>_<B_>_<Z_>,我想在数组中提取A, B, C

基本上_<是起始分隔符,_>是结束分隔符。

4 个答案:

答案 0 :(得分:5)

您可以使用lookaround assertions仅匹配代码的内容。

String text = "_<A_>_<B_>_<Z_>";

List<String> Result = new ArrayList<String>();

Pattern p = Pattern
    .compile("(?<=_<)" + // Lookbehind assertion to ensure the opening tag before
        ".*?" +          // Match a less as possible till the lookahead is true 
        "(?=_>)"         // Lookahead assertion to ensure the closing tag ahead
        );
Matcher m = p.matcher(text);
while(m.find()){
    Result.add(m.group(0));
}

答案 1 :(得分:3)

这很简单 - 切掉第一次打开和最后一次关闭,然后通过close-open

拆分
string.replaceFirst( "^_<(.*)_>$", "$1" ).split( "_>_<" );

答案 2 :(得分:-2)

您使用capture groups提取它们。

答案 3 :(得分:-2)

_<拆分以获得2个元素,取第2个并按_>拆分得到2个元素,取第1个并将其拆分为_>_<得到A,B, ç

相关问题