MillerMedia
MillerMedia

Reputation: 3671

Text Replacement With RegEx

I am using Sublime Text to write some Javascript and need to do a simple text replacement in the editor in order to set code up. I can do it manually but I figured there must be a way to have the replacement occur automatically with RegEx. I've used RegEx a bunch before but have never used it to grab data from one part of the code to reference and edit another part of the code. For example, I have this:

var example_1 = 836;
var example_2 = 837;
var example_3 = 838;
var example_4 = 846;

And then I have this:

SELECT_122=836
SELECT_143=837
SELECT_144=838
SELECT_145=846

I want these to use the corresponding values and format them like this:

SELECT_122: example_1,
SELECT_143: example_2,
SELECT_144: example_3,
SELECT_145: example_4

Note that I'm updating the equal signs to colons with spaces so I figured doing all these changes could be done with some sort of search and replace. I have a large amount of these so I figured it would be best to learn how to do this if it's possible.

Upvotes: 1

Views: 65

Answers (1)

zx81
zx81

Reputation: 41838

I don't have SublimeText, but you said in a comment that you want to do it through a text editor. Here is what works for me in EditPad Pro, it may work in Sublime.

Search:

(?s)(var (example_\d++) = (\d++).*?SELECT_\d++)=\3

Replace:

\1: \2,

Then I click "Replace". This will replace the first instance (SELECT_122=836) with "SELECT_122: example_1,"

Then I click "Replace Next" multiple times, and the SELECT_ strings are left looking like this:

SELECT_122: example_1,
SELECT_143: example_2,
SELECT_144: example_3,
SELECT_145: example_4,

Is this what you want?

Hope the regex and replacement string at least get you started. :)

Upvotes: 2

Related Questions