Java:了解 String ReplaceAll() 方法
我想在这里找到这个问题的答案。
首先,
blah[abc] = blah[abc].replaceAll("(.*) (.*)", "$2, $1");
有人可以向我解释一下 (.*)、$2 和 $1 是什么吗?
其次,当我将其嵌套在 for 语句中以反转字符串的两个部分时,我遇到了异常错误。我想知道是否有人知道这是为什么。
谢谢
编辑:这是我收到的错误
线程“main”java.lang.ArrayIndexOutOfBoundsException中的异常:1 在 ChangeNames.main(ChangeNames.java:21)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(.*) - 将是匹配任意数量字符的模式。括号将其标记为子模式(用于向后引用)。
2 美元$1 - 是反向引用。这些将是与您的第二个和第一个子模式匹配的内容。
基本上,replaceAll("(.) (.)", "$2, $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:
Not sure about nesting... Can you post the code you're running?
您的正则表达式“(.)(.)”将是这样的:“(x)(y)”这将被替换为“$2,$1”。
Your regular expression "(.)(.)" will be of this sort : "(x)(y)" this will be replaced by "$2,$1.