Sold Out
Sold Out

Reputation: 1428

How to replace a substring of a regular expression in text editor

This is my sample string:

(20,'7,8,9|1|X',1,1,1,1,1),
(81,'3',1,1,1,1,10),          
(83,'3',1,1,1,1,15),

My task is to replace "|X'" with "|X|X|X" ONLY where line starts with "(20,"

Using www.rubular.com I already got the reg ex. : ^(20,'.*)X' that matches this string: (20,'7,8,9|1|X' That means, replace command would replace whole strings matching my reg. Ex.

I can't figure out how to select just that substring "|X'" and replace only that.

Preferably, i'd like to use Notepad++ , if it is capable to replace reg-ex substrings.

Upvotes: 2

Views: 1684

Answers (4)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521053

Type the following into the Notepad++ Find/Replace window under "Find":

^(\(20,.*)(\|X)(.*\),)$

There are three capturing groups in the above regex. The first group (\(20,.*) matches everything before the |X, the second group (\|X) is what you are trying to find, and the third group (.*\),) is everything coming after the |X. The matches themselves are available as the variables $1, $2, and $3, corresponding to the first, second, and third group match from left to right.

Type the following into the "Replace" box:

$1\|X\|X\|X$3

This effectively replaces only what you want while preserving the rest of the line.

Here is a link where you can test the regex:

Regex101

And here is a link to the canonical Stack Overflow article discussing find/replace in Notepad++.

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You may replace using the following regex:

^(\(20,.*?\d)\|X'

And replace with $1|X|X|X'

If there are already replaced |Xs, this won't replace them.

Regex breakdown:

  • ^ - start of line
  • (\(20,.*?\d) - a group of....
    • \(20, - literal (20,
    • .*? - 0 or more characters other than a newline (as few as possible, *? is a lazy quantifier)
    • \d - a digit
  • \|X' - a literal |X'

Here is a screen with Notepad++ settings:

enter image description here

In the replacements string, we use back-references like $&, $1, etc. (not variables) and the pattern inside (...) is called a capturing group (not a match, a match is the whole text matched by the entire expression). More details can be found at regular-expressions.info.

Upvotes: 1

Mayur Koshti
Mayur Koshti

Reputation: 1852

re.sub(r"^(\(20,.*?)\|X(\'.*)$", r"\1|X|X|X\2", "(20,'7,8,9|1|X',1,1,1,1,1)")

Upvotes: -1

Magus
Magus

Reputation: 15104

Regular expression use groups to capture substring and, generally, editors/programmation langage use the syntax $n to use those groups. It means you can use this and replace with this : $1|X|X|X

Upvotes: 0

Related Questions