Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Understanding the String replaceAll() method

I'm looking to figure out the answer to this problem here.

First off,

blah[abc] = blah[abc].replaceAll("(.*) (.*)", "$2, $1");

Can someone explain to me what the (.*), $2 and $1 are?

Secondly, when I nest that within a for statement in order to reverse two parts of a string, I am hit with an exception error. I was wondering if anybody knew why that is.

Thanks

Edit: This is the error I receive

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at ChangeNames.main(ChangeNames.java:21)

like image 555
Jds Avatar asked Mar 04 '11 03:03

Jds


People also ask

What does in replaceAll () mean in Java?

The replaceAll() method replaces each substring of this string that matches the given regular expression with the given replacement.

What do the replaceAll () do?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement .

What does replaceAll return in Java?

The Java String replaceAll() returns a string after it replaces each substring of that matches the given regular expression with the given replacement.


1 Answers

(.*) - would be a pattern to match any number of characters. Parentheses would be to mark it as a sub pattern (for back reference).

$2 & $1 - are back references. These would be things matched in your second and first sub pattern.

Basically replaceAll("(.) (.)", "$2, $1") would find characters separated by a space, then add a comma before the space, in addition to flipping the parts. For example:

a b => b, a
Hello world => Hellw, oorld

Not sure about nesting... Can you post the code you're running?

like image 109
Sergey Avatar answered Nov 12 '22 19:11

Sergey