C# में Regex क्लास (Regular Expressions)
System.Text.RegularExpressions.Regex क्लास रेगुलर एक्सप्रेशन्स (पैटर्न मैचिंग) के लिए उपयोग होती है। यह टेक्स्ट सर्च, वैलिडेशन, पार्सिंग, रिप्लेसमेंट और स्प्लिटिंग के लिए शक्तिशाली टूल है।
Regex के मुख्य मेथड्स
| मेथड | विवरण | रिटर्न टाइप |
IsMatch(input) | पैटर्न मैच मिला? (बूलियन) | bool |
IsMatch(input, startat) | निर्दिष्ट पोजीशन से मैच जांचें | bool |
IsMatch(input, pattern) | स्टैटिक: पैटर्न और इनपुट दोनों पास करें | bool |
Match(input) | पहला मैच लौटाता है | Match |
Matches(input) | सभी मैचों का कलेक्शन | MatchCollection |
Replace(input, replacement) | मैच को रिप्लेसमेंट से बदलें | string |
Split(input) | पैटर्न पर स्ट्रिंग स्प्लिट करें | string[] |
उदाहरण: Matches() से शब्द खोजें
using System;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string text = "make maze and manage to measure it";
string pattern = @"\bm\S*e\b"; // 'm' से शुरू, 'e' पर खत्म होने वाले शब्द
Console.WriteLine("Matching words starting with 'm' and ending with 'e':");
MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match m in matches) {
Console.WriteLine(m.Value);
}
}
}
आउटपुट
Matching words starting with 'm' and ending with 'e':
make
maze
manage
measure
अन्य उपयोगी उदाहरण
Replace: डिजिट्स को मास्क करें
string input = "Card: 1234-5678-9012-3456";
string masked = Regex.Replace(input, @"\d", "X");
// "Card: XXXX-XXXX-XXXX-XXXX"
Split: एकाधिक डिलीमीटर्स पर स्प्लिट
string input = "apple,banana;orange|grape";
string[] fruits = Regex.Split(input, @"[,;|]");
// ["apple", "banana", "orange", "grape"]
कॉमन रेगुलर एक्सप्रेशन पैटर्न
| पैटर्न | मैच करता है |
\d | कोई डिजिट (0-9) |
\w | वर्ड कैरेक्टर (a-z, A-Z, 0-9, _) |
\s | व्हाइटस्पेस (स्पेस, टैब, न्यूलाइन) |
. | कोई कैरेक्टर (न्यूलाइन छोड़कर) |
^pattern | स्ट्रिंग की शुरुआत |
pattern$ | स्ट्रिंग का अंत |
pattern* | 0 या अधिक बार |
pattern+ | 1 या अधिक बार |
pattern? | 0 या 1 बार |
(pattern) | ग्रुपिंग/कैप्चरिंग |
प्रदर्शन टिप्स
- बार-बार उपयोग होने वाले पैटर्न के लिए
static readonly Regex या RegexOptions.Compiled उपयोग करें।
RegexOptions.IgnoreCase केस-इनसेंसिटिव के लिए।
- कैटास्ट्रोफिक बैकट्रैकिंग से बचें (नेस्टेड क्वांटिफायर्स)।