繁体   English   中英

java-使用正则表达式拆分字符串

[英]java - using regex to split string

我希望将此字符串“ Initial:At(Forest),MonsterAt(Chimera,Forest),Alive(Chimera)”解析为:“ At(Forest)”,“ MonsterAt(Chimera,Forest)”和“ Alive(Chimera)” )”(我不需要“ Initial:”)。

我使用了以下代码( java-使用正则表达式拆分字符串 ):

 String[] splitArray = subjectString.split(
        "(?x),   # Verbose regex: Match a comma\n" +
        "(?!     # unless it's followed by...\n" +
        " [^(]*  # any number of characters except (\n" +
        " \\)    # and a )\n" +
        ")       # end of lookahead assertion");

这是输出(下划线是空格):

Initial: At(Forest)
_MonsterAt(Chimera,Forest)
_Alive(Chimera)

但我不想在字符串(“ _Alive(Chimera)”)前留空格,并且我想在拆分后删除“ Initial:”。 如果我从原始字符串中删除了空格(“ Initial”除外),则输出为:

Initial: At(Forest),MonsterAt(Chimera,Forest),Alive(Chimera)

它不是正则表达式,但是在拆分返回数组之后,您可以执行以下操作:

splitArray[0] = splitArray[0].replace("Initial: ", "");
for(int el = 0; el < splitArray.length; el++){
    splitArray[el] = splitArray[el].trim();
}

您可以像这样在一行中完成整个操作:

String[] splitArray = str.replaceAll("^.*?: ", "").split("(?<=\\)), *");

在删除以冒号结尾的任何初始输入后,只需在右括号后用逗号分隔即可。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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