简体   繁体   English

如何在Notepad ++中使用正则表达式捕获和替换字符串

[英]How to capture and replace strings with regex in Notepad++

I try to capture and replace strings with regex in notepad++, but the result is not as expected. 我尝试在notepad ++中捕获并用正则表达式替换字符串,但是结果与预期的不同。 The database is formatted like this: 数据库的格式如下:

(602, '0602', '[{"id":"9","value":""},{"id":"1","value":"1"}]'),
(1644, '0164', '[{"id":"9","value":""},{"id":"1","value":"3"}]'),
(1311, '0131', '[{"id":"9","value":""},{"id":"1","value":"100"}]'),
(1321, '0132', '[{"id":"9","value":""},{"id":"1","value":"150"}]')

The task is to capture and place column 2 (values 0602, 0164, 0131, 0131) and to insert it as value of id 9. For example, end result must be like this: 任务是捕获并放置第2列(值0602、0164、0131、0131),并将其作为id 9的值插入。例如,最终结果必须像这样:

(602, '0602', '[{"id":"9","value":"0602"},{"id":"1","value":"1"}]'),
(1644, '0164', '[{"id":"9","value":"0164"},{"id":"1","value":"3"}]'),
(1311, '0131', '[{"id":"9","value":"0131"},{"id":"1","value":"100"}]'),
(1321, '0132', '[{"id":"9","value":"0132"},{"id":"1","value":"150"}]')

I try with this regex in Notepad++ - Search: 我在Notepad ++中尝试使用此正则表达式-搜索:

(, '.*)("id":"9","value":"")

Replace: 更换:

($1)("id":"9","value":"$1")

The result is close, but not what I need. 结果很接近,但不是我所需要的。 Please, help me if you know the right answer. 如果您知道正确的答案,请帮助我。 Thank you in advance. 先感谢您。

You can use below regex to capture the parts of the string and replace it by the second column value 您可以使用下面的正则表达式捕获字符串的各个部分,并将其替换为第二列的值

^(\(\d+,\s*.*?(\d+).*?value":).*?([,}])

And use \\1"\\2"\\3 as the replacement part. 并使用\\1"\\2"\\3作为替换零件。

Live Demo on RegEx101 RegEx101上的现场演示

Explanation: 说明:

  1. ^ : Start of line ^ :行首
  2. \\( : Match ( literal \\( :匹配(文字
  3. \\d+,\\s* : Match digit/s followed by comma and any number of spaces \\d+,\\s* :匹配数字/秒,后跟逗号和任意数量的空格
  4. .*? : Match anything to satisfy the following condition :匹配满足以下条件的任何内容
  5. (\\d+) : Match one or more digits and add them in captured group (\\d+) :匹配一个或多个数字并将其添加到捕获的组中
  6. .*?value": : Match till value" .*?value": ::匹配到value"
  7. ([,}]) : Match either , or } ([,}])匹配任一,}

The captured group \\1 will contain the string till value": , "\\2" will contain the number in the second column in double quotes and \\3 will contain the last , or } . 所捕获的组\\1将包含字符串直到value": "\\2"将包含在双引号在第二列的数目和\\3将包含最后,}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM