简体   繁体   中英

Java Regexp adding spaces to all characters after a part of string

I am trying to manipulate a string to a format of regexp

String months1 = "(?<month>(?i:January|February|March|April|May|June|July|August|September|October|November|December))";
String monthsResult = months1.replaceAll("([^\\(\\?\\<month\\>\\(\\?i])([a-zA-Z])", "$0 ?");

I would like to have the result in format that after (?<month>(?i: would every character have a whitespace, but the code above shows:

(?<month>(?i:J ?an ?ua ?ry ?|F ?eb ?ru ?ar ?y|M ?ar ?ch ?|A ?pr ?il|M ?ay ?|J ?un ?e|J ?ul ?y|A ?ug ?us ?t|S ?ep ?tem ?be ?r|O ?ct ?obe ?r|N ?ove ?mbe ?r|D ?ec ?em ?be ?r))

Is there something to do with the grouping or my replaceAll function regexp is not exact?

Any help would be appreciated.

The expected result would be

"(?<month>(?i:J ?a ?n ?u ?a ?r ?y|F ?e ?b ?r ?u ?a ?r ?y|M ?a ?r ?c ?h|A ?p ?r ?i ?l|M ?a ?y|J ?u ?n ?e|J ?u ?l ?y|A ?u ?g ?u ?s ?t|S ?e ?p ?t ?e ?m ?b ?e ?r|O ?c ?t ?o ?b ?e ?r|N ?o ?v ?e ?m ?b ?e ?r|D ?e ?c ?e ?m ?b ?e ?r))
.replaceAll("(?<=(?<=[A-Z])[a-z]*)([a-z])", " ?$1");

You could use an expression like:

(?<=\(\?<month>\(\?i:.{0,16000})\w\B

Replaced with $0 ? .

str.replaceAll("(?<=\\(\\?<month>\\(\\?i:.{0,16000})\\w\\B", "$0 ?");

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