Exploring the potential of VSCode's RegEx search and replace

I am working on an Angular translation file and need to perform a search and replace operation in VScode for the translate key. The goal is to extract only the final key and use it in the replacement. The keys are structured with a maximum depth of 3 levels. The terms key and keepThisInReplace in the examples below are placeholders that will vary.

Examples of Search Strings:

'key1.keepThisInReplace1' | translate
'key1.key2.keepThisInReplace2' | translate
'key1.key2.key3.keepThisInReplace3' | translate
'anyWord.AndLevelAmount.UpTo3AtLeast.anyWordToKeep' | translate

Do not include in the search:

'../../assets/images/
'./../assets/images/
'.......
'path').join
'staging.site
etc...

The replacements should be as follows:

'keepThisInReplace1' | translate
'keepThisInReplace2' | translate
'keepThisInReplace3' | translate
'anyWordToKeep' | translate

The pattern I have attempted, which is not yet functioning properly, looks like '\w[^.].\w*.*\w*. It almost works but captures unwanted instances such as 'path').join and 'staging.site.

All the keys mentioned above are preceded by {{. However, if I focus on {{ in my search criteria, then I also need to include it in the replacement. For example:

{{ key1.key2.keeptext | translate }}
would become {{ keeptext | translate }}

Answer №1

To match 1 to 3 occurrences of 1+ word characters followed by a dot in a non-capturing group, ensure multiline is enabled using the ^$ anchors.

When replacing, add a '

^'(?:\w+\.){1,3}(?=\w+'\s+\|\s+translate$)

If the string can be located anywhere in the file, remove the anchors and use a word boundary \b after translate.

'(?:\w+\.){1,3}(?=\w+'\s+\|\s+translate\b)

Detailed Explanation

  • ^ Indicates the start of the string
  • (?:\w+\.){1,3} Matches 1 to 3 occurrences of 1+ word characters and a dot
  • (?= Positive lookahead, verifying what comes after is
    • \w+'\s+ Matches 1+ word characters, ', and 1+ whitespace characters
    • \| Indicates |
    • \s+translate$ Matches 1+ whitespace characters, translate, and confirms end of the line
  • ) Closes positive lookahead

Check out the Regex demo here

Alternatively, you can opt for 2 capturing groups instead of a positive lookahead.

In the replacement, utilize group 1 and group 2 like this: $1$2

^(')(?:\w+\.){1,3}(\w+'\s+\|\s+translate$)

Explore the alternative Regex demo here

Answer №2

'.*\. is all you need to replace tick followed by any number of characters and a dot.

If you want to be more precise, you can try this:

'\w*\.*\w*\.*\w*\.

This regex will match strings with up to 3 dots and words in between them.

See the demo here:

EDIT

I made it more specific. Here's what I came up with:

'.+\.(?=\w*'\s*\|\s*translate)

It uses a lookahead to ensure the matched string is followed by a word and then ' | translate. Do you think this is specific enough?

Demo:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Activating controllers with 2 independent sliders

(Using the WordPress Slider Revolution plugin) I have set up two sliders next to each other - one displaying the service name and description, and the other showing images. The goal is for clicking a specific bullet on the service slider to also trigger t ...

When testing, Redux form onSubmit returns an empty object for values

Is it possible to pass values to the onSubmit handler in order to test the append function? Currently, it always seems to be an empty object. Test Example: const store = createStore(combineReducers({ form: formReducer })); const setup = (newProps) => ...

Personalize your Native Base tab design

Recently, I've delved into the world of React Native and now find myself in need of assistance with customizing my tabs. Utilizing advanced tabs by Native Base, I aim to transform this: https://i.stack.imgur.com/xhNwP.png Into something more akin ...

Using default JavaScriptSerializer to bind DateTime to knockout view model

Recently, I started using knockout and encountered a problem with DateTime Serialization and Deserialization when using the JavaScriptSerializer. I modified the gifts model in Steve's koListEditor example from his blog to include a new field for Modi ...

Using Typescript to add an element to a specific index in an array

Currently, I am engaged in a project using Angular2 and Firebase. My goal is to consolidate all query results under a single key called this.guestPush. Within my project, there is a multiple select element with different user levels - specifically 4, 6, ...

How can I load only specific images on a webpage using HTML?

I attempted to implement an image filter for my website by using the code below: <script> function myFunction() { // Initialize variables var input, filter, ul, li, a, i; input = document.getElementById('myInput'); filter = input.value.toU ...

Creating a 10-digit unique value can be achieved with either meteor or JavaScript

I am in need of generating 10 character unique codes, containing both letters and digits, to be utilized for system generated gift vouchers. Currently, the code I am using includes 13 numbers. var today = new Date(); Number(today); Is there a different m ...

The Material UI dialog box popped up against an unexpected gray backdrop

Currently, I am using Material UI in conjunction with React to create a dialog that appears when a button is tapped. This button is located within a table, which is displayed over a Paper component. The problem arises when I utilize the dialog with its def ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

Tips on implementing JSON data into select2 plugin

I have been trying to integrate the select2 plugin into my project. I followed a tutorial from this link, but unfortunately, it's not functioning properly for me. Here is the JSON output: [ {"ime":"BioPlex TM"}, {"ime":"Aegis sym agrilla"}, ...

NodeJS rendering method for HTML pages

We are in the process of developing a fully functional social networking website that will resemble popular platforms like Facebook or Instagram. Our plan is to utilize Node.js on the server side and we are currently exploring the best technology for rende ...

Unable to retrieve JSON element using Fetch

I'm attempting to retrieve a JSON file and exhibit its components within a div. Here is the JSON data I have: [ { "0":{ "host_id":"129230780", "host_names":"STK Homes", ...

Confirm that step attribute is applied to input of number type

When working with the following HTML code, I encounter a challenge with validating the step: <form name="myForm"> <input type="number" name="test" min={{min}} max={{max}} step={{step}}> <div class="error-popup" ng-if="myForm.test.$touched & ...

Use the Google Maps API to dynamically add a marker via AJAX once the map has been initialized

Although I have come across similar questions with related titles, none of the answers quite fit my needs. Here is the problem I am facing: I'm working on printing a map that contains multiple markers generated from a database. Below the map, there ...

Secure access to an API using a certificate within a Vue.js application running on localhost

My vue.js app is built using vue-cli. The application is hosted at dev.example.com and the REST API can be found at dev.example.com/api/v1/. The backend has added an SSL certificate for security on the development environment. However, when I try to make a ...

What is the method to display HTML code using JavaScript within a span element in a JSP page?

While working on a jsp file, I came across a span tag with the following code: <span id="divBasicSearchResults" style="height:100%;"></span> Below is the Javascript function that generates HTML content for this span: function renderBasicSear ...

Modify the URL parameter when a button is clicked

I want to apologize in advance for not providing more information. If the limited info is not enough, I will remove the question. There's a script that creates a search engine based on another dynamically generated script which is complex and beyond ...

Assign the value/text of a div element by using JavaScript/jQuery within a PHP loop

I'm struggling to figure out how to set the value/text of a div using javascript/jquery inside a loop. Can anyone offer some guidance on this issue? Goals: Extract data from a database. Use javascript/jquery to assign the extracted data to an eleme ...

Guide to Establishing a Connection to WCF Service using Ionic Project and AngularJS

Greetings, I am currently experiencing an issue tasked with connecting my Ionic project to a WCF service located on another PC (running a C# Application) within the local network. I have verified that the network connection between the PCs is functioning p ...

Is there a way to prevent prettier from automatically adding a new line when formatting HTML tags with ">"?

While navigating through the Prettier extension in Vscode, I am struggling to find a way to disable a specific scenario. In particular, I am having trouble with the formatting of an html tag. Below is a snippet of code that requires some adjustments whene ...