简体   繁体   中英

String.split with ** crashes

I come across a very strange problem when doing a split on a String. The second line of the code below crashes:

String[] parts1 = "2 xy 3".split("xy"); //OK!
String[] parts2 = "2 ** 3".split("**"); //CRASHES java.util.regex.PatternSyntaxException: Syntax error in regexp pattern near index 1: **

Try this:

String[] parts2 = "2 ** 3".split("\\*\\*");

The problem is that the * has a special meaning in regex patterns, so the workaround is to use double-slash(since single slash would demand an escape character) before a *

For more info on how regex works in java, probably my slide on SlideShare would be useful.

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