Java: understanding String replaceAll () method

I want to find the answer to this problem here.

Primarily,

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

Can someone explain to me that (. *), $ 2 and $ 1?

Secondly, when I set the for statement inside to cancel the two parts of the line, I ended up with an exception error. I was wondering if anyone knows why this is.

thanks

Edit: this is the error I get

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

+4
source share
2 answers

(. *) - will be a template to match any number of characters. The brackets will mark it as an additional template (for a backlink).

$ 2 and $ 1 are backlinks. These will be the things matching your second and first pattern.

Basically replaceAll ("(.) (.)", "$ 2, $ 1") will find characters separated by a space, then add a comma before the space, and also flip the parts. For instance:

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

Not sure about nesting ... Can you post the code you use?

+10
source

Your regular expression "(.) (.)" Will be of this type: "(x) (y)" it will be replaced with "$ 2, $ 1.

-1
source

Source: https://habr.com/ru/post/1342223/


All Articles