Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing only the first space in a string

Tags:

java

I want to replace the first space character in a string with another string listed below. The word may contain many spaces but only the first space needs to be replaced. I tried the regex below but it didn't work ...

Pattern inputSpace = Pattern.compile("^\\s", Pattern.MULTILINE);  
String spaceText = "This split ";    
System.out.println(inputSpace.matcher(spaceText).replaceAll(" "));

EDIT:: It is an external API that I am using and I have the constraint that I can only use "replaceAll" ..

like image 807
Phoenix Avatar asked Jan 29 '26 12:01

Phoenix


2 Answers

Your code doesn't work because it doesn't account for the characters between the start of the string and the white-space.

Change your code to:

Pattern inputSpace = Pattern.compile("^([^\\s]*)\\s", Pattern.MULTILINE);  
String spaceText = "This split ";    
System.out.println(inputSpace.matcher(spaceText).replaceAll("$1 "));

Explanation:

[^...] is to match characters that don't match the supplied characters or character classes (\\s is a character class).

So, [^\\s]* is zero-or-more non-white-space characters. It's surrounded by () for the below.

$1 is the first thing that appears in ().

Java regex reference.

The preferred way, however, would be to use replaceFirst: (although this doesn't seem to conform to your requirements)

String spaceText = "This split ";
spaceText = spaceText.replaceFirst("\\s", " ");
like image 95
Bernhard Barker Avatar answered Jan 31 '26 00:01

Bernhard Barker


You can use the String.replaceFirst() method to replace the first occurence of the pattern

System.out.println(" all test".replaceFirst("\\s", "test"));

And String.replaceFirst() internally calls Matcher.replaceFirst() so its equivalent to

Pattern inputSpace = Pattern.compile("\\s", Pattern.MULTILINE);  
String spaceText = "This split ";    
System.out.println(inputSpace.matcher(spaceText).replaceFirst(" "));
like image 35
sanbhat Avatar answered Jan 31 '26 00:01

sanbhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!