Java regex for specific case -
i trying reformat string desired format. have been trying figure out while can't think of elegant solution using regexs. have come solution using string's indexof()
, replace()
it's not pretty.
i want convert string there 1 space on each side of "-".
possible inputs:
"abc- abc" "abc -abc" "abc - abc" "abc-abc"
and each case should converted to
"abc - abc"
thanks help. let me know if need more clarification.
using string#replaceall
:
string pattern = "\\s*-\\s*"; string s1 = "abc- abc"; string s2 = "abc -abc"; string s3 = "abc - abc"; string s4 = "abc-abc"; system.out.println(s1.replaceall(pattern, " - ")); system.out.println(s2.replaceall(pattern, " - ")); system.out.println(s3.replaceall(pattern, " - ")); system.out.println(s4.replaceall(pattern, " - "));
explanation of "\\s*-\\s*"
regex:
\\s
=> space (in fact,\s
java needs double\\
)*
=> 0 or more-
=> simple '-'
more info regular expressions: regular expression basic syntax reference
Comments
Post a Comment