📅  最后修改于: 2023-12-03 14:39:43.887000             🧑  作者: Mango
In C#, regular expressions can be used to manipulate strings by defining patterns that match one or more characters. In this code example, we will be using a regular expression to identify specific letters within a string and double them.
Here is an example C# code snippet that demonstrates how to double specific letters in a string using regular expressions:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "This is a sample string.";
string pattern = "([aeiou])";
string replacement = "$1$1";
string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("New String: {0}", result);
}
}
The using
statement imports the System
and System.Text.RegularExpressions
namespaces.
The Main
method sets up a sample string, input
, and the regular expression pattern, pattern
, and the replacement string, replacement
.
In the regular expression pattern, ([aeiou])
matches any of the letters in the set aeiou
and captures it into group 1.
The replacement string "$1$1"
uses the capture group 1 twice to double the matched letters.
The Regex.Replace
method is called with the input
, pattern
, and replacement
strings as arguments. This method returns a new string with all matches replaced.
The original input
string and the new string result
are printed to the console.
When you run this code, you should see the following output:
Original String: This is a sample string.
New String: Thhiis is aa saammppllee strinng.
In this code example, we used regular expressions to identify specific letters within a string and double them. Regular expressions can be a powerful tool for manipulating strings in C#.