简体   繁体   中英

java - using regex to split string

I want this string "Initial: At(Forest), MonsterAt(Chimera,Forest), Alive(Chimera)" to be parsed into: "At(Forest)" , "MonsterAt(Chimera, Forest)" , and "Alive(Chimera)" (I don't need "Initial:").

I used this code from ( java - split string using regular expression ):

 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");

this is the output (the underscore is a space):

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

but I don't want to have a space before the string ("_Alive(Chimera)"), and I want to remove the "Initial: " after splitting. If I removed the spaces (except for "Initial") from the original string the output is this:

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

It's not regex, but after your split returns an array you could do:

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

You can do the whole thing in one line like this:

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

This works by simply splitting on commas following closing brackets, after removing any initial input ending in colon-space.

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