增量替换数字数字模式?

问题描述 投票:0回答:11

假设我想要 10 行数据,但我想要为每行或每条数据递增一个值。如何增加该值?

例如...如果我有这些行,是否有正则表达式方法来替换 id 值以递增?

<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />

--- 这是我希望它看起来像的样子...(如果第一行的 id 上升了就可以了)

<row id="1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5" />
regex notepad++ sequential
11个回答
176
投票

不确定正则表达式,但有一种方法可以让您在 Notepad++ 中执行此操作,尽管它不是很灵活。

在您提供的示例中,按住

Alt
并选择您要更改的数字列。然后转到
Edit->Column Editor
并在出现的窗口中选择
Number to Insert
单选按钮。然后指定您的初始数字和增量,然后单击“确定”。它应该写出递增的数字。

注意:这也适用于

Multi-editing
功能(在按住 Ctrl 键的同时选择多个位置)。

然而,这远未达到大多数人认为有用的灵活性。 Notepad++ 很棒,但如果你想要一个真正强大的编辑器,可以轻松完成这样的事情,我会建议使用 Vim。


18
投票

我今天正在寻找相同的功能,但在 Notepad++ 中无法做到这一点。不过,我们有 TextPad 来救援。这对我有用。

在TextPad的替换对话框中,打开正则表达式;那你可以尝试更换

<row id="1"/>

<row id="\i"/>

查看此链接,了解 TextPad 的更多令人惊叹的替换功能 - http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/


15
投票

我在超过 250 行时遇到了同样的问题,这是我的做法:

例如:

<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />
<row id="1" />

将光标放在“1”后面,然后单击

alt + shift
并开始使用向下箭头下降,直到到达底线,现在您看到一组选择,单击擦除以同时擦除每行上的数字 1,转到
Edit -> Column Editor
并选择
Number to Insert
,然后将
1
放入初始数字字段,将
1
放入递增字段,检查零数字,然后单击
ok

恭喜你做到了:)


6
投票

由于真正的答案有限,我将分享这个解决方法。对于真正简单的情况,比如你的例子,你可以向后做......

从这里

1
2
3
4
5

\r\n
替换为
" />\r\n<row id="
,你将完成 90% 的任务

1" />
<row id="2" />
<row id="3" />
<row id="4" />
<row id="5

或者是一种类似的方式,您可以使用 Excel/电子表格来处理数据。只需将原始数据拆分为列并根据需要操作值即可。

|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |
|   <row id="   |   1   |   " />    |

显而易见的东西,但它可能会帮助某人做奇怪的一次性黑客工作,以节省一些击键。


4
投票

http://docs.notepad-plus-plus.org/index.php/Inserting_Variable_Text

Notepad++ 配备了编辑 -> 列“Alt+C”编辑器,可以通过两种不同的方式处理矩形选择: Coledit.png 在插入点(也称为插入符号)的列处(包括当前行及其之后的每一行)插入一些固定文本。最初选择的文本保持不变。 如图所示,可以以相同的方式插入一系列线性数字。应提供起始值和增量。可以选择用零向左填充,并且可以以 2、8、10 或 16 为基数输入数字 - 这也是计算值的显示方式,填充基于最大值。


4
投票

如果您将值存储在文件 input.txt:

中,您可以使用 Powershell 通过正则表达式和 foreach 循环来完成此操作
$initialNum=1; $increment=1; $tmp = Get-Content input.txt | foreach {  $n = [regex]::match($_,'id="(\d+)"').groups[1
].value; if ($n) {$_ -replace "$n", ([int32]$initialNum+$increment); $increment=$increment+1;} else {$_}; }

之后,您可以使用

$tmp > result.txt
将 $tmp 存储在文件中。这不需要数据位于列中。


3
投票


上述建议的解决方案仅在数据对齐时才有效。
使用 PythonScript Notepad++ 插件查看链接中的解决方案,效果很好!

stackoverflow 查找/替换但递增值


1
投票

(发布以防有人可能使用它)。

我正在寻找一个比OP更复杂的问题的解决方案 - 将每一次出现的数字替换为相同的数字递增的数字

例如更换这样的东西:

<row id="1" />
<row id="2" />
<row id="1" />
<row id="3" />
<row id="1" />

通过这个:

<row id="2" />
<row id="3" />
<row id="2" />
<row id="4" />
<row id="2" />

无法在网上找到解决方案,所以我用 groovy 编写了自己的脚本(有点难看,但可以完成工作):

 /**
 * <p> Finds words that matches template and increases them by 1.
 * '_' in word template represents number.
 *
 * <p> E.g. if template equals 'Row="_"', then:
 * ALL Row=0 will be replaced by Row="1"
 * All Row=1 will be replaced by Row="2"
 * <p> Warning - your find template might not work properly if _ is the last character of it
 * etc.
 * <p> Requirments:
 * - Original text does not contain tepmlate string
 * - Only numbers in non-disrupted sequence are incremented and replaced
 * (i.e. from example below, if Row=4 exists in original text, but Row=3 not, than Row=4 will NOT be 
 * replaced by Row=5)
 */
def replace_inc(String text, int startingIndex, String findTemplate) {
    assert findTemplate.contains('_') : 'search template needs to contain "_" placeholder'
    assert !(findTemplate.replaceFirst('_','').contains('_')) : 'only one "_" placeholder is allowed'
    assert !text.contains('_____') : 'input text should not contain "______" (5 underscores)'
    while (true) {
        findString = findTemplate.replace("_",(startingIndex).toString())
        if (!text.contains(findString)) break;
        replaceString = findTemplate.replace("_", "_____"+(++startingIndex).toString())
        text = text.replaceAll(findString, replaceString)
    }
    return text.replaceAll("_____","") // get rid of '_____' character
}

// input
findTemplate = 'Row="_"'
path = /C:\TEMP\working_copy.txt/
startingIndex = 0

// do stuff
f = new File(path)
outText = replace_inc(f.text,startingIndex,findTemplate)
println "Results \n: " + outText
f.withWriter { out -> out.println outText }
println "Results written to $f"

1
投票

由于我们现在正在玩代码高尔夫,所以这里是用 C# 编写的。您可以根据您的具体情况修改

Replace()

        public void Do(string inputPath, string outputPath, string key)
        { 
            var index = 0;
            var output = new List<string>();
            string[] lines = File.ReadAllLines(inputPath);
            foreach (var line in lines)
            {
                if (line.Contains(key))
                {
                    output.Add(line.Replace(key, $"{key} {index++}, "));
                }
                else
                {
                    index = 0;
                    output.Add(line);
                }
            }

            File.WriteAllLines(outputPath, output);
        }

-1
投票

您可以在 Python 中使用这个非常相似的脚本。这是一个非常好的代码。只需将

$item_id = abc;
更改为您的
<row id="abc" />
(根据您的情况)

import os
import re
 
def read_text_from_file(file_path):
    """
    Aceasta functie returneaza continutul unui fisier.
    file_path: calea catre fisierul din care vrei sa citesti
    """
    with open(file_path, encoding='utf8') as f:
        text = f.read()
        return text
 
 
def write_to_file(text, file_path):
    """
    Aceasta functie scrie un text intr-un fisier.
    text: textul pe care vrei sa il scrii
    file_path: calea catre fisierul in care vrei sa scrii
    """
    with open(file_path, 'wb') as f:
        f.write(text.encode('utf8', 'ignore'))
 
def incrementare_fisiere_html(cale_folder_html):
    """
    Functia itereaza printr-un folder care contine fisiere html si adauga index-ul corespunzator in fiecare fisier
    """
    count = 0
    current_id = 1
    for f in os.listdir(cale_folder_html):
            if f.endswith('.html'):
                cale_fisier_html = cale_folder_html + "\\" + f
                html_text = read_text_from_file(cale_fisier_html)
                item_id_pattern = re.compile('\$item_id = (.*?);')
                item_id = re.findall(item_id_pattern, html_text)
                if len(item_id) > 0:
                    print("{} a fost modificat. ".format(f))
                    item_id = item_id[0]
                    html_text = html_text.replace(item_id, str(current_id))
                    current_id += 1
                    count += 1
                    write_to_file(html_text, cale_fisier_html)
                else:
                    # print("{} nu are $item_id.".format(f))
                    continue
            else:
                continue
    print("Numarul de fisiere modificate: ", count)
 
if __name__ == '__main__':
    # sa pui calea catre folderul cu fisiere
    incrementare_fisiere_html('e:\\Folder1')

解释和源代码点击这里:


-1
投票

Python 的简单版本,用于测试:

# Initial data
data = [
    '<row id="1" />',
    '<row id="1" />',
    '<row id="1" />',
    '<row id="1" />',
    '<row id="1" />'
]

# Incrementing the id value
incremented_data = [f'<row id="{i+1}" />' for i in range(len(data))]

# Print the result
for row in incremented_data:
    print(row)

下面的代码用于替换文件:

import os
import re

def increment_row_id_in_file(file_path, id_value):
    print(f"Procesez fișierul: {file_path}")

    # Citirea conținutului fișierului
    with open(file_path, 'r', encoding='utf8') as file:
        content = file.read()

    # Incrementarea valorii id în tag-ul <row>
    row_id_pattern = re.compile(r'(<row id=")\d+(" />)')
    incremented_content = row_id_pattern.sub(lambda m: f"{m.group(1)}{id_value}{m.group(2)}", content)

    # Rescrierea conținutului înapoi în fișier
    with open(file_path, 'w', encoding='utf8') as file:
        file.write(incremented_content)

    print(f"Înlocuit id cu {id_value} în {file_path}")

# Calea către directorul cu fișiere HTML
directory_path = 'c:\\Folder-Oana\\extracted\\translated'

# Procesarea fiecărui fișier HTML din director și incrementarea id-ului
id_value = 1
for filename in os.listdir(directory_path):
    if filename.endswith('.html'):
        file_path = os.path.join(directory_path, filename)
        increment_row_id_in_file(file_path, id_value)
        id_value += 1  # Incrementare pentru următorul fișier
© www.soinside.com 2019 - 2024. All rights reserved.