java - Replacing only the first space in a string -


i want replace first space character in string string listed below. word may contain many spaces first space needs replaced. tried regex below didn't work ...

pattern inputspace = pattern.compile("^\\s", pattern.multiline);   string spacetext = "this split ";     system.out.println(inputspace.matcher(spacetext).replaceall(" ")); 

edit:: external api using , have constraint can use "replaceall" ..

your code doesn't work because doesn't account characters between start of string , white-space.

change code to:

pattern inputspace = pattern.compile("^([^\\s]*)\\s", pattern.multiline);   string spacetext = "this split ";     system.out.println(inputspace.matcher(spacetext).replaceall("$1 ")); 

explanation:

[^...] match characters don't match supplied characters or character classes (\\s character class).

so, [^\\s]* zero-or-more non-white-space characters. it's surrounded () below.

$1 first thing appears in ().

java regex reference.

the preferred way, however, use replacefirst: (although doesn't seem conform requirements)

string spacetext = "this split "; spacetext = spacetext.replacefirst("\\s", " "); 

Comments