2 using System.Collections.Generic;
5 using System.Threading.Tasks;
6 using System.Text.RegularExpressions;
8 namespace System.Web.Util {
9 internal class RegexUtil {
11 // this method is for the regex match which accepts the pattern from developer
12 // since asp.net doesn't have control of the regex pattern string and it is possible
13 // to take more than 2 sec to match a string, give developer option to set timeout value
14 public static bool IsMatch(string stringToMatch, string pattern, RegexOptions regOption, int? timeoutInMillsec) {
15 int timeout = GetRegexTimeout(timeoutInMillsec);
17 if (timeout > 0 || timeoutInMillsec.HasValue) {
18 return Regex.IsMatch(stringToMatch, pattern, regOption, TimeSpan.FromMilliseconds((double)timeout));
20 return Regex.IsMatch(stringToMatch, pattern, regOption);
24 public static Match Match(string stringToMatch, string pattern, RegexOptions regOption, int? timeoutInMillsec) {
25 int timeout = GetRegexTimeout(timeoutInMillsec);
27 if (timeout > 0 || timeoutInMillsec.HasValue) {
28 return Regex.Match(stringToMatch, pattern, regOption, TimeSpan.FromMilliseconds((double)timeout));
30 return Regex.Match(stringToMatch, pattern, regOption);
34 public static Regex CreateRegex(string pattern, RegexOptions option, int? timeoutInMillsec) {
35 int timeout = GetRegexTimeout(timeoutInMillsec);
37 if (timeout > 0 || timeoutInMillsec.HasValue) {
38 return new Regex(pattern, option, TimeSpan.FromMilliseconds((double)timeout));
40 return new Regex(pattern, option);
44 // This method is for the regex asp.net controls the regex pattern and it should NOT take longer than 2 secs to match the string
45 // so no need for developer to specify a timeout value
46 internal static Regex CreateRegex(string pattern, RegexOptions option) {
47 return CreateRegex(pattern, option, null);
50 private static bool? _isRegexTimeoutSetInAppDomain;
51 private static bool IsRegexTimeoutSetInAppDomain {
53 if (!_isRegexTimeoutSetInAppDomain.HasValue) {
54 bool timeoutSetInAppDomain = false;
56 timeoutSetInAppDomain = AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT") != null;
59 _isRegexTimeoutSetInAppDomain = timeoutSetInAppDomain;
61 return _isRegexTimeoutSetInAppDomain.Value;
65 private static int GetRegexTimeout(int? timeoutInMillsec) {
68 // here is the logic for using timeout in regex
69 // 1. if the caller sets a timeout value, then we use it(this may cause Regex throw ArgumentOutOfRangeException,
70 // but developer will know what they need to do when seeing the exception)
71 // 2. if there is global setting in AppDomain, we do nothing(leave it to Regex to handle the timeout)
72 // 3. if the web app targets to 4.6.1+, then we set 2 secs timeout
73 if (timeoutInMillsec.HasValue) {
74 timeout = timeoutInMillsec.Value;
76 if (!IsRegexTimeoutSetInAppDomain && BinaryCompatibility.Current.TargetsAtLeastFramework461) {