6

I try to capture and replace strings with regex in notepad++, but the result is not as expected. 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:

(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:

(, '.*)("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.

1 Answer 1

9

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.

Live Demo on RegEx101

Explanation:

  1. ^: Start of line
  2. \(: Match ( literal
  3. \d+,\s*: Match digit/s followed by comma and any number of spaces
  4. .*?: Match anything to satisfy the following condition
  5. (\d+): Match one or more digits and add them in captured group
  6. .*?value":: Match till 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 }.

4
  • Be careful, you are missing the quotation after the value in the replacement.
    – Lery
    Jun 7, 2017 at 11:33
  • @Tushar, thank you very much for solution and for explanation. I will try it immediately. Jun 7, 2017 at 11:39
  • @Tushar 100% working solution. I modify it slyghtly like this: Search: ^((\d+,\s*.*?(\d+).*?value":").*?([,}]) Replace: \1\2"\3 Thanks again! Jun 7, 2017 at 11:50
  • 1
    Nice! now I understand the function of '(' ')' Thanks! Feb 6, 2019 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.