Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print first letter of each word in a string using C# regex
In C#, you can use regular expressions to extract the first letter of each word from a string. This technique uses the Regex.Matches() method with a specific pattern to identify word boundaries and capture the initial characters.
Syntax
The regular expression pattern to match the first letter of each word is −
@"\b[a-zA-Z]"
Where −
-
\b− represents a word boundary -
[a-zA-Z]− matches any single letter (uppercase or lowercase)
The Regex.Matches() method syntax −
MatchCollection matches = Regex.Matches(inputString, pattern);
How It Works
The word boundary \b ensures we only match letters that start a new word, not letters in the middle of words. This makes the pattern highly effective for extracting word initials.
Example
using System;
using System.Text.RegularExpressions;
namespace RegExApplication {
public class Program {
private static void showMatch(string text, string expr) {
Console.WriteLine("The Expression: " + expr);
MatchCollection mc = Regex.Matches(text, expr);
foreach (Match m in mc) {
Console.WriteLine(m);
}
}
public static void Main(string[] args) {
string str = "The Shape of Water got an Oscar Award!";
Console.WriteLine("Display first letter of each word!");
showMatch(str, @"\b[a-zA-Z]");
}
}
}
The output of the above code is −
Display first letter of each word! The Expression: \b[a-zA-Z] T S o W g a O A
Alternative Approach Using String Join
You can also combine all first letters into a single string −
using System;
using System.Text.RegularExpressions;
using System.Linq;
class Program {
public static void Main() {
string str = "The Shape of Water got an Oscar Award!";
Console.WriteLine("Original string: " + str);
MatchCollection matches = Regex.Matches(str, @"\b[a-zA-Z]");
string firstLetters = string.Join("", matches.Cast<Match>().Select(m => m.Value));
Console.WriteLine("First letters: " + firstLetters);
}
}
The output of the above code is −
Original string: The Shape of Water got an Oscar Award! First letters: TSoWgaOA
Common Use Cases
Creating acronyms − Extract initials to form abbreviations
Text processing − Analyze document structure by examining word patterns
Data validation − Check if text follows specific formatting rules
Search optimization − Create searchable indexes based on word initials
Conclusion
Using the regex pattern \b[a-zA-Z] with Regex.Matches() is an efficient way to extract the first letter of each word in a string. The word boundary \b ensures precise matching at the start of words, making this approach reliable for text processing tasks.
