What is the correct format for passing regex expression like ![,?.\_'@+] in Java String split method? -
i have ff. delimeters ![,?.\_'@+]
in str.split("![,?.\_'@+]")
. but, cause error when program compiled states \_
illegal escape character. have tried remove , pass ![,?.'@+]
instead, string not being split if contains ?, @ , .
character.
you need put symbols character class , escape [
, ]
, \
there:
str.split("[!\\[,?.\\\\_'@+\\]]")
the [!\\[,?.\\\\_'@+\\]]
character class matches single character set specified (!
, [
, ,
, ?
, .
, \
, _
, '
, @
, +
, or ]
).
note _
not special regex metacharacter , not have (and should not be) escaped. if need add \
character character class, need use 4 backslashes match literal \
in input.
note whenever need add hyphen regex, should put right @ beginning or end of character class. please refer splitting string using multiple delimiters java dwells on problem of how match hyphen inside character class in java regex.
if want rid of empty elements in resulting array, replace split characters @ start of string, , apply +
(one or more occurrences) quantifier character class (here updated answer whitespace added character class):
str.replaceall("^[!\\[,?.\\\\_'@+\\]\\s]+, "").split("[!\\[,?.\\\\_'@+\\]\\s]+")
Comments
Post a Comment