使用单词拆分字符串,但保留每个数组索引中的单词

Kyl*_*ine 2 java regex string split

以下代码,

            String string = "<xml attributes>some xml code</xml>"
                            + "<xml attributes>some xml code</xml>"
                            + "<xml attributes>some xml code</xml>"
                            + "<xml attributes>some xml code</xml>";

            String[] stringArray = string.split("<xml");

            for ( String i : stringArray) {

                System.out.println(i);
            }
Run Code Online (Sandbox Code Playgroud)

打印

 attributes>some xml code</xml>
 attributes>some xml code</xml>
 attributes>some xml code</xml>
 attributes>some xml code</xml>
Run Code Online (Sandbox Code Playgroud)

但我想保留每个数组索引中的< xml字,以便输出,

 <xml attributes>some xml code</xml>
 <xml attributes>some xml code</xml>
 <xml attributes>some xml code</xml>
 <xml attributes>some xml code</xml>
Run Code Online (Sandbox Code Playgroud)

The*_*ind 5

稍微改变你的代码以使用积极的lookbehind.

String[] stringArray = string.split("(?<=</xml>)");

O/P:

<xml attributes>some xml code</xml>
<xml attributes>some xml code</xml>
<xml attributes>some xml code</xml>
<xml attributes>some xml code</xml>
Run Code Online (Sandbox Code Playgroud)

  • 确实非常优雅! (2认同)