取代前20次出现

时间:2017-01-04 15:29:19

标签: regex notepad++

我需要在下一行

中捕获(替换)前20位数字(逗号之前)
11112222333344445555, 123456

并在数字之间插入逗号。我尝试添加(\d)(\d) ... (\d) 20次并替换为\1,\2, ... \20,但失败了。我是否可以使用记事本++了解更好的方法。

3 个答案:

答案 0 :(得分:3)

<强>查找

(?<a>\d)(?<b>\d)(?<c>\d)(?<d>\d)(?<e>\d)(?<f>\d)(?<g>\d)(?<h>\d)(?<i>\d)(?<j>\d)(?<k>\d)(?<l>\d)(?<m>\d)(?<n>\d)(?<o>\d)(?<p>\d)(?<q>\d)(?<r>\d)(?<s>\d)(?<t>\d)

<强>替换

${a},${b},${c},${d},${e},${f},${g},${h},${i},${j},${k},${l},${m},${n},${o},${p},${q},${r},${s},${t}

proof of concept

现在所有这一切......对于较大n的类似问题,您可能最好使用迭代/编程方法(使用您选择的语言)而不是单次拍摄&#34;查找/替换&#34;正则表达式操作。

Java中的示例:

String input = /* some string */;

Pattern pattern = Pattern.compile("^\\d+");
Matcher matcher = pattern.matcher(input);
String match = matcher.group();

StringBuilder sb = new StringBuilder(match.length()*2);
for (char ch : match.toCharArray()) {
    sb.append(ch);
    sb.append(',');
}
String replacement = sb.substring(0,sb.length()-1);

String result = replacement + input.subString(match.length());

答案 1 :(得分:2)

对于编号大于9的捕获组,您应该使用${10} ${11} ...

- 找到什么:(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d) - 替换为:$1,$2,$3,$4,$5,$6,$7,$8,$9,${10},${11},${12},${13},${14},${15},${16},${17},${18},${19},${20}

但是对于更多的数字来说它是不可维护的,我建议您使用:

  • 找到:(?<![ \d])\d(?!,)
  • 替换为:$0,

答案 2 :(得分:2)

我找到了一个不需要命名组的解决方案:

  • 搜索(\d)(\d)...(\d)
  • 替换为$1, $2, ... $9, $10, ... $20

如果有助于消除表达式的歧义,您可以将反引用号括在大括号中:$11${11}都引用第11个表达式,而${1}1引用第1个反向引用后跟角色1

语法在Notepad++'s documentation中描述,但请注意不要在替换字段中尝试使用搜索语法(\g{n})!