正则表达式用顺序号替换字符串

时间:2019-04-30 03:01:06

标签: regex

我想知道是否有一个正则表达式为带有数字前缀的大约1000个条目的列表添加前缀,就像这样:

现有列表:

  

foo
  酒吧
  foob​​ar

所需的输出:

  

name1 = foo
  name2 = bar
  name3 = foobar

是否存在允许增加数字的正则表达式匹配模式?

我的搜索字段为(.+)(带有。不匹配换行符)

替换字段为name=\1

请注意,该文件的设置类似于ini文件,因此它具有节名,例如“ [section]”,我将跳过这些行。

然后,我将使用VBscript脚本添加数字,但是我想避免使用它,并尽可能使用regex替换字符串。

2 个答案:

答案 0 :(得分:3)

您不需要正则表达式。 Notepad ++具有“列编辑器”实用程序;您应该使用它。

  1. 将光标置于行首。
  2. 打开Edit菜单,然后选择Column Editor。它将打开以下窗口:

    Column Editor

  3. 选择Text to Insert,键入“名称”,然后单击确定。您的文字应如下所示:

    namefoo 
    namebar 
    namefoobar
    
  4. 将光标放在第一行中的“名称”一词之后。
  5. 重复步骤1和2。
  6. 选择Number to Insert,然后在前两个字段中分别输入11。如果需要,可以选中Leading zeros复选框。
  7. 现在,单击确定,您应该一切顺利。

答案 1 :(得分:0)

基于评论,我提出了一个VBscript来处理它。对于有相同问题的人:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "infile.txt"
strTemp = "outfile.ini"
Set objFile = objFS.GetFile(strFile)
Set objOutFile = objFS.CreateTextFile(strTemp,True)
Set ts = objFile.OpenAsTextStream(1,-2)
c=0
Do Until ts.AtEndOfStream
    Inp = ts.ReadLine
    if trim(Inp) ="" then 
        'nothing
    elseif left(Inp, 1)<>"[" then 
        c=c+1
        Inp="name" & Cstr(c) & "=" & Inp
    else
        'each section "[section]" restarts numbering
        c=0
    end if
    objOutFile.WriteLine(Inp)
Loop
objOutFile.Close
ts.Close