11// (c) 2019 SharpCoding
22// This code is licensed under MIT license (see LICENSE.txt for details)
3+ using System ;
34using System . Text . RegularExpressions ;
45
56namespace SharpCoding . SharpHelpers
@@ -14,8 +15,56 @@ public static class RegexHelper
1415 /// <returns></returns>
1516 public static bool IsMatchRegex ( this string value , string pattern )
1617 {
18+ if ( value == null ) throw new ArgumentNullException ( nameof ( value ) ) ;
19+ if ( pattern == null ) throw new ArgumentNullException ( nameof ( pattern ) ) ;
20+
1721 var regex = new Regex ( pattern ) ;
18- return ( regex . IsMatch ( value ) ) ;
22+ return regex . IsMatch ( value ) ;
23+ }
24+
25+ /// <summary>
26+ /// Retrieves the first match found in the input string.
27+ /// </summary>
28+ /// <param name="input">The input string to search.</param>
29+ /// <param name="pattern">The regular expression pattern.</param>
30+ /// <returns>The first match found, or null if no match is found.</returns>
31+ public static string Match ( this string input , string pattern )
32+ {
33+ if ( input == null ) throw new ArgumentNullException ( nameof ( input ) ) ;
34+ if ( pattern == null ) throw new ArgumentNullException ( nameof ( pattern ) ) ;
35+
36+ var match = Regex . Match ( input , pattern ) ;
37+ return match . Success ? match . Value : null ;
38+ }
39+
40+ /// <summary>
41+ /// Replaces all occurrences of a pattern with a replacement string.
42+ /// </summary>
43+ /// <param name="input">The input string to modify.</param>
44+ /// <param name="pattern">The regular expression pattern.</param>
45+ /// <param name="replacement">The replacement string.</param>
46+ /// <returns>A new string with all occurrences replaced.</returns>
47+ public static string Replace ( this string input , string pattern , string replacement )
48+ {
49+ if ( input == null ) throw new ArgumentNullException ( nameof ( input ) ) ;
50+ if ( pattern == null ) throw new ArgumentNullException ( nameof ( pattern ) ) ;
51+ if ( replacement == null ) throw new ArgumentNullException ( nameof ( replacement ) ) ;
52+
53+ return Regex . Replace ( input , pattern , replacement ) ;
54+ }
55+
56+ /// <summary>
57+ /// Splits a string into an array of substrings using a regex pattern as a delimiter.
58+ /// </summary>
59+ /// <param name="input">The input string to split.</param>
60+ /// <param name="pattern">The regular expression pattern to use as a delimiter.</param>
61+ /// <returns>An array of substrings.</returns>
62+ public static string [ ] Split ( this string input , string pattern )
63+ {
64+ if ( input == null ) throw new ArgumentNullException ( nameof ( input ) ) ;
65+ if ( pattern == null ) throw new ArgumentNullException ( nameof ( pattern ) ) ;
66+
67+ return Regex . Split ( input , pattern ) ;
1968 }
2069 }
2170}
0 commit comments