Allgemein
Nice2Know: Search and replace with value from search
Posted on .Sometimes you want to achieve a simple task like searching for something and replace something else but want the replaced text to contain the found text – sounds complicated, let me show you an example:
I have the input (on the left) and want to transform it to the format on the right:
Now imagine you have 90.000 of those entries, so copy & paste is not something you want to do.
Regular Expressions to the rescue
You can easily achieve this using very simple regular expressions, all you need is an editor which supports this functionality like Notepad++ (which I’m using in this example).
Select Search -> Replace… in the menu (or just hit Ctrl + H on the keyboard)
Make sure you select „regular expression“ at the bottom. Now you can define a regular expression in the „Find what“ textbox.
A short explanation of the search entry above:
In my case I’m looking for a undefined amount of numbers \d+ until a minus – occurs and then again for a undefined amount of numbers \d+. By wrapping this expression in braces () you make the result available to the „Replace with“ textbox.
Now we can use the first result \1 of the find-query above to place it inside the „Replace with:“ text.
If you want to split the found value and use different find results you can do so by splitting the „Find What“ query like this:
As you can see we have two results inside the „Find what“ query, we separate the digits before the minus from the ones after the minus and use the frst entry for the value of the id-parameter and he second for the value of the system-tag.
This is the result of the second replace:
As you can see this feature is very powerful and your imagination is the only limit 🙂
Sebastian Gross
http://www.bigbasti.comSebastian Gross arbeitet in Bielefeld als Softwareentwickler für .NET und Java im Bereich Web.Als Fan der .NET-Plattform lässt er sich kein Userguppen Treffen und Community Event im Raum OWL entgehen.Dabei hat er eine besondere Vorliebe für das ASP.NET MVC Framework und für das Test Driven Development (TDD) entwickelt.
There are no comments.