Java: Understanding the String replaceAll() method

左心房为你撑大大i 提交于 2019-12-21 05:06:54

问题


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)


回答1:


(.*) - 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?




回答2:


Your regular expression "(.)(.)" will be of this sort : "(x)(y)" this will be replaced by "$2,$1.



来源:https://stackoverflow.com/questions/5189415/java-understanding-the-string-replaceall-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!