[英]Append a digit in front of another digit between /s?
我有一串像这样的琴弦
/files/etc/hosts/2/ipaddr
/files/etc/hosts/2/canonical
/files/etc/hosts/2/alias[1]
/files/etc/hosts/3/ipaddr
/files/etc/hosts/3/canonical
/files/etc/hosts/3/alias[1]
/files/etc/hosts/4/ipaddr
/files/etc/hosts/4/canonical
/files/etc/hosts/4/alias[1]
我想在/
和/
之间的任何数字前添加一个0。 追加后,结果应如下所示...
/files/etc/hosts/02/ipaddr
/files/etc/hosts/02/canonical
/files/etc/hosts/02/alias[1]
/files/etc/hosts/03/ipaddr
/files/etc/hosts/03/canonical
/files/etc/hosts/03/alias[1]
/files/etc/hosts/04/ipaddr
/files/etc/hosts/04/canonical
/files/etc/hosts/04/alias[1]
我很确定我需要使用一个简单的正则表达式进行搜索。 我认为/\\d*/
应该足够了,但是我不确定如何修改字符串以插入数字0。有人可以给我一些建议吗?
采用:
newString = string.replaceAll("/(\\d)(?=/)", "/0$1");
\\\\d
仅一位数字。 随意将\\\\d+
用于一个或多个数字。
$1
表示字符串中与第一个单词匹配的部分,出现在方括号中(有些例外),即(\\\\d)
。
您需要使用前瞻(?=...)
而不是/(\\\\d)/
因为否则
/files/etc/hosts/3/5/canonical
会变成
/files/etc/hosts/03/5/canonical
代替
/files/etc/hosts/03/05/canonical
(如果不使用前瞻功能,则在匹配3的过程中会消耗3到5之间的/
,因此在5上不会匹配)。
如果上面的字符串不是可能的输入,那么这不是问题(您可以简单地使用/(\\\\d)/
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.