Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex: Match a character followed by whitespace?

Tags:

java

regex

This is driving me nuts... I have an input string like so:

String input = "T ";

And I'm trying to match and replace the string with something like so:

String output = input.replace("T\\s", "argggghhh");
System.out.println(output);  // expected: "argggghhh"
                             // actual: "T "

What am I doing wrong? Why won't the \\s match the space?

Keep in mind I want to match multiple white space characters (\\s+), but I can't get this simple case to work :(.

like image 816
Polaris878 Avatar asked Dec 08 '25 01:12

Polaris878


1 Answers

Use replaceAll() instead of replace().

replace() does not use regular expressions.

See http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replace(java.lang.CharSequence, java.lang.CharSequence) vs. http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String)

like image 59
Christian Kuetbach Avatar answered Dec 10 '25 14:12

Christian Kuetbach



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!