简体   繁体   English

Java:了解String replaceAll()方法

[英]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? 有人可以向我解释一下(。*),$ 2和$ 1是什么?

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. 其次,当我在for语句中嵌套以便反转字符串的两个部分时,我遇到异常错误。 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) 线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:1在ChangeNames.main(ChangeNames.java:21)

(.*) - 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. $ 2和$ 1 - 是后参考。 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. 基本上replaceAll(“(。 )(。 )”,“$ 2,$ 1”)会找到用空格分隔的字符,然后在空格之前添加逗号,以及翻转部分。 For example: 例如:

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

Not sure about nesting... Can you post the code you're running? 不确定嵌套...你能发布你正在运行的代码吗?

您的正则表达式“(。)(。)”将是这种类型:“(x)(y)”这将被替换为“$ 2,$ 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM