Java:了解 String replaceAll() 方法 [英] Java: Understanding the String replaceAll() method

查看:57
本文介绍了Java:了解 String replaceAll() 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这里找出这个问题的答案.

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

首先,

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

谁能向我解释一下 (.*)、$2 和 $1 是什么?

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

其次,当我将它嵌套在 for 语句中以反转字符串的两个部分时,我遇到了异常错误.我想知道是否有人知道这是为什么.

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.

谢谢

这是我收到的错误

线程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 - 是反向引用.这些将与您的第二个和第一个子模式匹配.

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

基本上replaceAll("(.) (.)", "$2, $1") 会查找由空格分隔的字符,然后在空格前添加逗号,除了翻转部分.例如:

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?

这篇关于Java:了解 String replaceAll() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆