简体   繁体   中英

Java: Javascript-like split behavior

I have a javascript code like:

var tmp = "abcdefg";
alert(tmp.split(/(b)(c)/));

which gives me

[a,b,c,defg]

which is what i want, but when I did it in Java, it only splits the string removing the matching regex.

String tmp = "abcdefg";
tmp.split("(b)(c)"));

which gives me

[a,defg]

How can I make the split in Java behave like the split in javascript?

In Java use lookahead based regex:

"abcdefg".split( "(?=[bc])|(?<=[bc])" );

Code:

String[] toks = "abcdefg".split( "(?=[bc])|(?<=[bc])" );
for (String tok: toks)
    System.out.printf("<%s>%n", tok);

Output:

<a>
<b>
<c>
<defg>

如您所见,您无法在Java中的正则表达式拆分中保持捕获组,但是可以编写:

(?=bc)|(?<=b)(?=c)|(?<=bc)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM