Learn how to locate and substitute every designated character instance, whether using C# or regex. Discover the process of converting code from Javascript to C#

Locate and substitute the 3rd instance of each character in a given string with H

For example: 74Mercedes1980 would become 74HerHedHs1H80

This task can be accomplished using C# or regex.

I have come across a Javascript script that achieves this, but I am looking to translate it into C#. Can you provide assistance?

Source found at here

str = str.replace(/((?:[^x]*x){2}[^x]*)x/g, '$1y');

let str = 'I amx nexver axt hoxme on Sxundxaxs';
let n = 3;
let ch = 'x';

let regex = new RegExp("((?:[^" +ch+ "]*" +ch+ "){" + (n-1) + "}[^" +ch+ "]*)" +ch, "g");

str = str.replace(regex, '$1y');

console.log(str);
//=> I amx nexver ayt hoxme on Sxundyaxs

Answer №1

You have the ability to capture 2 non-whitespace characters using \S and match the 3rd non-whitespace character.

When replacing, utilize the captured group followed by the specific character you want in the replacement text.

If there is a need to include a space as well, a dot . can be used instead of \S

let str = '74Mercedes1980';
let n = 3;
let ch = 'H';
let regex = new RegExp("(\\S{" + (n - 1) + "})\\S", "g");
str = str.replace(regex, `$1${ch}`);
console.log(str);

This can also be achieved in C# as follows:

var str = "74Mercedes1980";
var n = 3;
var ch = 'H';
var regex = new Regex("(\\S{" + (n - 1) + "})\\S");
str = regex.Replace(str, "$1" + ch);
Console.WriteLine(str);

Output

74HerHedHs1H80

For a demonstration in C#, check out this C# demo

Answer №2

The example with predefined values translates to

var re = new Regex("((?:[^x]*x){2}[^x]*)x");
var result = re.Replace("I amx nexver axt hoxme on Sxundxaxs", m => m.Groups[1] + "y");

This can also be expressed as

var ch = 'x';
var n = 3;
var str = "I amx nexver axt hoxme on Sxundxaxs";
var re = new Regex("((?:[^" +ch+ "]*" +ch+ "){" + (n-1) + "}[^" +ch+ "]*)" +ch);
var result = re.Replace(str, m => m.Groups[1] + "y");
Console.WriteLine(result);

For a working demo, visit: https://dotnetfiddle.net/u8mJrn

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

Issue with clicking element in Selenium WebDriver using C# (element not empty)

I've encountered an issue where I can't click on an element inside a box that is filled by ajax. On the web page I'm using, there's a link that, when clicked, calls a JavaScript function to insert a new div filled with content. I can l ...

Modify/Adjust/Move the image uploaded by the user in VueJS before transferring it to an aws s3 bucket

Can you resize images in vuejs using vanilla js? I've managed to upload an image and send it to my s3 bucket using vue, but I'm struggling to figure out how to transform an image within vuejs and display it. Document.querySelector doesn't se ...

Upon extracting files from MS SQL, they appear to be corrupt and unreadable

I am facing a problem with my ASP MVC app, MS SQL, and C#. I download a file to MS SQL, then upload the file from the database. However, after this process, the file becomes unreadable. I am unable to figure out what is causing this issue. Below is the c ...

How can I retrieve data during a double-click event in Kendo Grid using Angular?

How can I retrieve data on the doubleClick event in a Kendo Grid? I want to access the same object that is fetched during the selected event, which would be the dataitem at the selected index row. HTML: <kendo-grid #myGrid [data]="gridDat ...

Firebase enables email verification and user login for secure access to the page

I have developed a form "main.html#!/register" where users can input their first name, last name, email, and login details. Once these details are entered, an email verification is sent before they can proceed to the page "main.html#!/success". The positi ...

Utilizing $resource within a promise sequence to correct the deferred anti-pattern

One challenge I encountered was that when making multiple nearly simultaneous calls to a service method that retrieves a list of project types using $resource, each call generated a new request instead of utilizing the same response/promise/data. After doi ...

What is the best way to combine two sections in html/css/bootstrap?

I've been trying to create a simple webpage with a navigation bar and a section below it, but I keep running into an issue where there's unwanted white space between the nav bar and the next section in blue. Is there a way to eliminate this gap a ...

Is it possible to create a constructor for an Enum in Java?

I recently wrote the code below and it compiled successfully: class Program { enum Fruits { Apple, Mango, Banana } static void Main(string[] args) { Fruits f = new Fr ...

Guide to conducting distributed calculations using F# (.Net)

Recently, I experimented with the Async library in F# and was truly impressed by the functionality of Async.Parallel. This feature allows for combining a sequence of Async tasks into one unified Async task. Now, I find myself wondering about distributing ...

Using JavaScript to display a live data table on a website sourced from Firebase

I am trying to generate a table with data from Google Firebase in JavaScript, but for some reason the table is not being displayed. Below is the code I am using: <a href="#usertable" onclick="openLink(event,'usertable');tab1();" class="tabl ...

Guide on smoothly scrolling to an anchor point using Adobe Edge animations

Struggling to find a solution to my simple problem. I want to create an animated button on my website that scrolls to a specific anchor point on the same page. The code I currently have in Edge's code snippet box isn't working as expected. It&ap ...

Verifying assigned role and running a specified task

I have a task to verify if a user possesses a specific role, and if they do, to remove it. If the user does not have the role, then display a certain message. let user = message.guild.member(message.mentions.users.first() || message.guild.members.get(args ...

Error encountered when attempting to use the Find function on a custom object, due to

I'm a bit puzzled by this situation. Trying to locate a property in a custom object that begins with specific text is proving to be challenging for me. Interestingly, when I attempt to search for a property using == instead of StartsWith, it does no ...

What could be causing the unclickable radio button in XAML using MAUI on Android?

I am facing an issue with my page that requires users to choose between two options with the help of a radio button. To maintain formatting consistency, I created a custom ControlTemplate for the radio button so it matches our overall design. Below is the ...

Is there a possibility of encountering an endless update loop within a component's render function?

Hello! I am a beginner in Vue.js and I have encountered an issue with my function. Instead of increasing my variable to 1 as expected, it is increasing it to a random number every time. The console is displaying the following error message: "You may hav ...

The Image Button within Grid view is failing to trigger in an ASP.NET Web form

When using an ASP.NET Web form, I am experiencing an issue where the Image Button inside a Grid View is not firing. However, if I switch to using an ASP Button, it works seamlessly and is easy to add. Below is the design code for the grid view Button: &l ...

What is the best method to transfer a password securely to a server using Vue or JavaScript?

I've developed Vue components for both login and registration functionalities. Now, I'm faced with the question of how to securely send passwords to the server. Should I encrypt the password using bcrypt on the client side before sending it to La ...

How should one properly utilize the app and pages directories in a next.js project?

For my current next.js 13 project, I have decided to utilize the /pages directory instead of /app. Nonetheless, I recently included the app directory specifically for its new features related to dynamic sitemap rendering. Do you think this approach is app ...

Angularjs regex filter: applying regular expressions to filter data

I've created a regex pattern to match URLs like this: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ Now, I need to incorporate this regex into a filter that will specifically extra ...

Utilizing Metalness with the MTLLoader in three.js

Lately, I've been utilizing MTLLoader to load my obj meshes in Threejs. Although it does the job by loading the correct textures, the material appears too dull for my liking. My expectation: https://i.sstatic.net/Z2T9d.png What I am currently seei ...