System.Text.RegularExpressions.Regex.IsMatch(string, string)

Here are the examples of the csharp api System.Text.RegularExpressions.Regex.IsMatch(string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1488 Examples 7

19 View Source File : RegexTextBoxBehavior.cs
License : MIT License
Project Creator : aliprogrammer69

private void OnPaste(object sender, DataObjectPastingEventArgs e) {
            if (e.DataObject.GetDataPresent(DataFormats.Text)) {
                string text = Convert.ToString(e.DataObject.GetData(DataFormats.Text));
                if (!Regex.IsMatch(text, Expersion))
                    e.CancelCommand();
            }
            else
                e.CancelCommand();

        }

19 View Source File : StringExtension.cs
License : MIT License
Project Creator : AlphaYu

public static bool IsMatch([NotNull] this string input, string pattern) => Regex.IsMatch(input, pattern);

19 View Source File : StringUtilities.cs
License : MIT License
Project Creator : AdrianWilczynski

public static bool IsValidIdentifier(this string text)
            => Regex.IsMatch(text, "^([a-zA-Z_$][0-9a-zA-Z_$]*|[0-9]+)$");

19 View Source File : FixClassName.cs
License : MIT License
Project Creator : alexjhetherington

private static void replaceClreplacedName(string clreplacedName, string scriptPath)
        {
            try
            {
                String[] fileText = File.ReadAllLines(scriptPath);

                for (int i = 0; i < fileText.Length; i++)
                {
                    // make the refactoring only if the clreplaced name is different
                    if (Regex.IsMatch(fileText[i], @"\bclreplaced\b"))
                    {
                        if (Regex.IsMatch(fileText[i], "\\b" + clreplacedName + "\\b"))
                        {
                            Debug.Log(noRefactoringMessage);
                            return; // skip if the name is the same
                        }

                        // match the identifier of a clreplaced so it can be replaced by 'clreplacedName'
                        // we use a Positive Lookbehind...
                        String regexPattern = @"(?<=clreplaced )\w+";
                        fileText[i] = Regex.Replace(fileText[i], regexPattern, clreplacedName);
                        File.WriteAllLines(scriptPath, fileText);

                        Debug.Log(refactoringMessage);
                    }
                    else if (Regex.IsMatch(fileText[i], @"\binterface\b"))
                    {
                        if (Regex.IsMatch(fileText[i], "\\b" + clreplacedName + "\\b"))
                        {
                            Debug.Log(noRefactoringMessage);
                            return; // skip if the name is the same
                        }

                        // match the identifier of a clreplaced so it can be replaced by 'clreplacedName'
                        // we use a Positive Lookbehind...
                        String regexPattern = @"(?<=interface )\w+";
                        fileText[i] = Regex.Replace(fileText[i], regexPattern, clreplacedName);
                        File.WriteAllLines(scriptPath, fileText);

                        Debug.Log(refactoringMessage);
                    }
                }
            }
            catch (Exception exc) { Debug.Log(String.Format(errorMessage, exc.Message)); }
        }

19 View Source File : HttpRoute.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void ProcessRequest(HttpListenerRequest Request, HttpListenerResponse Response, string prefix = null)
		{
			string url = Request.Url.AbsolutePath;
			var rule = _rules.Find(r => Regex.IsMatch(url, r.Pattern));
			url = Regex.Replace(url, rule.Pattern, rule.Replace);
			Response.Redirect(url);
		}

19 View Source File : EmbeddedResourceAssemblyAttribute.cs
License : MIT License
Project Creator : Adoxio

private string ConvertVirtualPathToResourceName(string virtualPath)
		{
			// converting an entire path
			// for all parts: prepend an '_' if the name starts with a numeric character
			// replace all '/' or '\\' with '.'
			// prepend the default namespace
			// besides a leading underscore, filenames remain unchanged

			var parts = virtualPath.Split(_directoryDelimiters, StringSplitOptions.RemoveEmptyEntries);

			if (parts.Any())
			{
				var partsWithUnderscores = parts.Select(p => Regex.IsMatch(p, @"^\d") ? "_" + p : p);
				var directories = partsWithUnderscores.Take(parts.Length - 1).Select(ConvertDirectoryToResourceName);
				var head = directories.Aggregate(Namespace, (h, d) => "{0}.{1}".FormatWith(h, d)).Replace('-', '_');
				var tail = partsWithUnderscores.Last();
				return "{0}.{1}".FormatWith(head, tail);
			}

			return null;
		}

19 View Source File : GridifyMapper.cs
License : MIT License
Project Creator : alirezanet

public IGridifyMapper<T> AddMap(string from, Expression<Func<T, int, object?>> to, Func<string, object>? convertor = null!,
         bool overrideIfExists = true)
      {
         if (!overrideIfExists && HasMap(from))
            throw new GridifyMapperException($"Duplicate Key. the '{from}' key already exists");

         RemoveMap(from);
         var isNested = Regex.IsMatch(to.ToString(), @"\.Select\s*\(");
         _mappings.Add(new GMap<T>(from, to, convertor, isNested));
         return this;
      }

19 View Source File : TabooTableEntry.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public bool ContainsBadWord(string input)
        {
            // Our entire banned patterns list should be lower case
            input = input.ToLower();

            // First, we need to split input into separate words
            var words = input.Split(' ');

            foreach (var word in words)
            {
                foreach (var bannedPattern in BannedPatterns)
                {
                    if (Regex.IsMatch(word, "^" + bannedPattern.Replace("*", ".*") + "$"))
                        return true;
                }
            }

            return false;
        }

19 View Source File : Guard.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static void replacedertValidAppRepoName(string repoName)
        {
            if (string.IsNullOrEmpty(repoName) || !Regex.IsMatch(repoName, @"^(?!datamodels$)[a-z]+[a-z0-9-]+[a-z0-9]$"))
            {
                throw new ArgumentException($"The repository name {repoName} is invalid.");
            }
        }

19 View Source File : MoneyFormatter.cs
License : MIT License
Project Creator : Adoxio

private bool GetCurrencySymbolComesFirst()
		{
			return Regex.IsMatch(
				new decimal(1.00).ToString("C", _culture),
				string.Format(@"^\s*{0}", Regex.Escape(_culture.NumberFormat.CurrencySymbol)));
		}

19 View Source File : UserServiceExtensions.cs
License : MIT License
Project Creator : albyho

private static bool IsValidMobile(string source)
        {
            return Regex.IsMatch(source, @"^(1\d{10})$");
        }

19 View Source File : JsonValidatingReader.cs
License : MIT License
Project Creator : akaskela

private void ValidateString(JsonSchemaModel schema)
        {
            if (schema == null)
            {
                return;
            }

            if (!TestType(schema, JsonSchemaType.String))
            {
                return;
            }

            ValidateNotDisallowed(schema);

            string value = _reader.Value.ToString();

            if (schema.MaximumLength != null && value.Length > schema.MaximumLength)
            {
                RaiseError("String '{0}' exceeds maximum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MaximumLength), schema);
            }

            if (schema.MinimumLength != null && value.Length < schema.MinimumLength)
            {
                RaiseError("String '{0}' is less than minimum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MinimumLength), schema);
            }

            if (schema.Patterns != null)
            {
                foreach (string pattern in schema.Patterns)
                {
                    if (!Regex.IsMatch(value, pattern))
                    {
                        RaiseError("String '{0}' does not match regex pattern '{1}'.".FormatWith(CultureInfo.InvariantCulture, value, pattern), schema);
                    }
                }
            }
        }

19 View Source File : LocalFileSystem.cs
License : MIT License
Project Creator : Adoxio

private bool TryGetFullPath(string templatePath, out string fullPath)
		{
			fullPath = null;

			if (templatePath == null || !Regex.IsMatch(templatePath, @"^[a-zA-Z0-9_][a-zA-Z0-9_\/]*$"))
			{
				return false;
			}

			try
			{
				fullPath = templatePath.Contains("/")
					? Path.Combine(Path.Combine(Root, Path.GetDirectoryName(templatePath)), "{0}.liquid".FormatWith(Path.GetFileName(templatePath)))
					: Path.Combine(Root, "{0}.liquid".FormatWith(templatePath));

				var escapedPath = Root.Replace(@"\", @"\\").Replace("(", @"\(").Replace(")", @"\)");

				return Regex.IsMatch(Path.GetFullPath(fullPath), "^{0}".FormatWith(escapedPath));
			}
			catch (System.ArgumentException)
			{
				return false;
			}
		}

19 View Source File : BuildProcessCallbacksHandler.cs
License : Apache License 2.0
Project Creator : Algoryx

public static bool IsOutOfInstallDependency( string modulePath )
    {
      foreach ( var dependency in m_ooiDependencies ) {
        var moduleFileInfo = new FileInfo( modulePath );
        if ( System.Text.RegularExpressions.Regex.IsMatch( moduleFileInfo.Name, dependency ) ) {
          return true;
        }
      }
      return false;
    }

19 View Source File : HexColorField.cs
License : MIT License
Project Creator : 734843327

public static bool HexToColor(string hex, out Color32 color)
    {
        // Check if this is a valid hex string (# is optional)
        if (System.Text.RegularExpressions.Regex.IsMatch(hex, hexRegex))
        {
            int startIndex = hex.StartsWith("#") ? 1 : 0;

            if (hex.Length == startIndex + 8) //#RRGGBBAA
            {
                color = new Color32(byte.Parse(hex.Substring(startIndex, 2), NumberStyles.AllowHexSpecifier),
                    byte.Parse(hex.Substring(startIndex + 2, 2), NumberStyles.AllowHexSpecifier),
                    byte.Parse(hex.Substring(startIndex + 4, 2), NumberStyles.AllowHexSpecifier),
                    byte.Parse(hex.Substring(startIndex + 6, 2), NumberStyles.AllowHexSpecifier));
            }
            else if (hex.Length == startIndex + 6)  //#RRGGBB
            {
                color = new Color32(byte.Parse(hex.Substring(startIndex, 2), NumberStyles.AllowHexSpecifier),
                    byte.Parse(hex.Substring(startIndex + 2, 2), NumberStyles.AllowHexSpecifier),
                    byte.Parse(hex.Substring(startIndex + 4, 2), NumberStyles.AllowHexSpecifier),
                    255);
            }
            else if (hex.Length == startIndex + 4) //#RGBA
            {
                color = new Color32(byte.Parse("" + hex[startIndex] + hex[startIndex], NumberStyles.AllowHexSpecifier),
                    byte.Parse("" + hex[startIndex + 1] + hex[startIndex + 1], NumberStyles.AllowHexSpecifier),
                    byte.Parse("" + hex[startIndex + 2] + hex[startIndex + 2], NumberStyles.AllowHexSpecifier),
                    byte.Parse("" + hex[startIndex + 3] + hex[startIndex + 3], NumberStyles.AllowHexSpecifier));
            }
            else  //#RGB
            {
                color = new Color32(byte.Parse("" + hex[startIndex] + hex[startIndex], NumberStyles.AllowHexSpecifier),
                    byte.Parse("" + hex[startIndex + 1] + hex[startIndex + 1], NumberStyles.AllowHexSpecifier),
                    byte.Parse("" + hex[startIndex + 2] + hex[startIndex + 2], NumberStyles.AllowHexSpecifier),
                    255);
            }
            return true;
        }
        else
        {
            color = new Color32();
            return false;
        }
    }

19 View Source File : LoginViewModel.cs
License : MIT License
Project Creator : aliprogrammer69

public bool CanConfirm() =>
            !string.IsNullOrEmpty(_confirmCode) &&
            !ShowProgress &&
            _confirmCode.Length >= 4 &&
            Regex.IsMatch(_confirmCode, "^\\d*$");

19 View Source File : FileSystem.cs
License : MIT License
Project Creator : AdrianWilczynski

public static bool EndsWithFileExtension(this string text)
            => Regex.IsMatch(text, @"\.\w+$");

19 View Source File : IPHelper.cs
License : MIT License
Project Creator : alonsoalon

public static bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

19 View Source File : JcApiHelperUIMiddleware.cs
License : MIT License
Project Creator : 279328316

public async Task Invoke(HttpContext httpContext)
        {
            string httpMethod = httpContext.Request.Method;
            string path = httpContext.Request.Path.Value.ToLower();

            if (httpMethod == "GET" && Regex.IsMatch(path, $"/apihelper/"))
            {
                if (Regex.IsMatch(path, $"/apihelper/index.html"))
                {   //index.html特殊处理
                    await RespondWithIndexHtml(httpContext.Response);
                    return;
                }
                else
                {
                    string resourceName = path.Replace($"/apihelper/", "")
                                            .Replace("/", ".");
                    if (!apiResources.Any(a => a.ToLower() == $"{embeddedFileNamespace}.{resourceName}".ToLower()))
                    {   // 处理刷新界面
                        await RespondWithIndexHtml(httpContext.Response);
                        return;
                    }
                }
            }
            await staticFileMiddleware.Invoke(httpContext);
        }

19 View Source File : ApplicationsController.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

[ApiExplorerSettings(IgnoreApi = true)]
        public bool IsValidAppId(string appId)
        {
            if (string.IsNullOrEmpty(appId))
            {
                return false;
            }

            string[] parts = appId.Split("/");

            if (parts.Length != 2)
            {
                return false;
            }

            string orgNamePattern = @"^[a-zæøå][a-zæåø0-9]*$";
            if (!Regex.IsMatch(parts[0], orgNamePattern))
            {
                return false;
            }

            string appPattern = @"^[a-zæøå][a-zæøå0-9\-]*$";
            if (!Regex.IsMatch(parts[1], appPattern))
            {
                return false;
            }

            return true;
        }

19 View Source File : RegexValidator.cs
License : MIT License
Project Creator : afucher

public bool Validate(string value)
        {
            return Regex.IsMatch(value, pattern);
        }

19 View Source File : RegExSample.cs
License : The Unlicense
Project Creator : ahotko

private void IsMatchSnipet()
        {
            string pattern = @"^This sentence";
            string sentenceYes = $"This sentence is a match.";
            string sentenceNo = $"This weird sentence is not a match.";

            Console.WriteLine($"The sentence '{sentenceYes}' is {(Regex.IsMatch(sentenceYes, pattern) ? "" : "not")} a match to pattern '{pattern}'");
            Console.WriteLine($"The sentence '{sentenceNo}' is {(Regex.IsMatch(sentenceNo, pattern) ? "" : "not")} a match to pattern '{pattern}'");
        }

19 View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099

public string GetMySqlEnumSetDefine()
	{
		if (fsql.Ado.DataType != FreeSql.DataType.MySql && fsql.Ado.DataType != FreeSql.DataType.OdbcMySql) return null;
		var sb = new StringBuilder();
		foreach (var col in table.Columns)
		{
			if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
			{
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append("\r\n\t[Flags]");
				sb.Append($"\r\n\tpublic enum {this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}");
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append(" : long");
				sb.Append(" {\r\n\t\t");

				string slkdgjlksdjg = "";
				int field_idx = 0;
				int unknow_idx = 0;
				string exp2 = string.Concat(col.DbTypeTextFull);
				int quote_pos = -1;
				while (true)
				{
					int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
					if (quote_pos == -1) break;
					while (true)
					{
						quote_pos = exp2.IndexOf('\'', quote_pos + 1);
						if (quote_pos == -1) break;
						int r_cout = 0;
						//for (int p = 1; true; p++) {
						//	if (exp2[quote_pos - p] == '\\') r_cout++;
						//	else break;
						//}
						while (exp2[++quote_pos] == '\'') r_cout++;
						if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/)
						{
							string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 2).Replace("''", "'");
							if (Regex.IsMatch(str2, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$"))
								slkdgjlksdjg += ", " + str2;
							else
								slkdgjlksdjg += string.Format(@", 
/// <summary>
/// {0}
/// </summary>
[Description(""{0}"")]
Unknow{1}", str2.Replace("\"", "\\\""), ++unknow_idx);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
								slkdgjlksdjg += " = " + Math.Pow(2, field_idx++);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum && field_idx++ == 0)
								slkdgjlksdjg += " = 1";
							break;
						}
					}
					if (quote_pos == -1) break;
				}
				sb.Append(slkdgjlksdjg.Substring(2).TrimStart('\r', '\n', '\t'));
				sb.Append("\r\n\t}");
			}
		}
		return sb.ToString();
	}

19 View Source File : HttpRoute.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public bool IsMatch(HttpListenerRequest Request, string prefix)
		{
			string url = Request.GetFilePath(prefix);
			return _rules.Exists(r => Regex.IsMatch(url, r.Pattern));
		}

19 View Source File : SharePointDataAdapter.cs
License : MIT License
Project Creator : Adoxio

public ISharePointResult AddFolder(EnreplacedyReference regarding, string name, string folderPath = null)
		{
			var context = _dependencies.GetServiceContextForWrite();
			var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
			var result = new SharePointResult(regarding, enreplacedyPermissionProvider, context);

			if (string.IsNullOrWhiteSpace(name)) return result;

			// Throw exception if the name begins or ends with a dot, contains consecutive dots,
			// or any of the following invalid characters ~ " # % & * : < > ? / \ { | }
			if (Regex.IsMatch(name, @"(\.{2,})|([\~\""\#\%\&\*\:\<\>\?\/\\\{\|\}])|(^\.)|(\.$)"))
			{
				throw new Exception("The folder name contains invalid characters. Please use a different name. Valid folder names can't begin or end with a period, can't contain consecutive periods, and can't contain any of the following characters: ~  # % & * : < > ? / \\ { | }.");
			}

			var enreplacedyMetadata = context.GetEnreplacedyMetadata(regarding.LogicalName);
			var enreplacedy = context.CreateQuery(regarding.LogicalName).First(e => e.GetAttributeValue<Guid>(enreplacedyMetadata.PrimaryIdAttribute) == regarding.Id);

			// replacedert permission to create the sharepointdoreplacedentlocation enreplacedy
			if (!result.PermissionsExist || !result.CanCreate || !result.CanAppend || !result.CanAppendTo)
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Enreplacedy Permissions to Create or Append doreplacedent locations or AppendTo the regarding enreplacedy.");
				return result;
			}

			var spConnection = new SharePointConnection(SharePointConnectionStringName);
			var spSite = context.GetSharePointSiteFromUrl(spConnection.Url);

			var location = GetDoreplacedentLocation(context, enreplacedy, enreplacedyMetadata, spSite);

			// replacedert permission to write the sharepointdoreplacedentlocation enreplacedy
			if (!result.CanWrite)
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Enreplacedy Permissions to Write doreplacedent locations.");
				return result;
			}

			var factory = new ClientFactory();

			using (var client = factory.CreateClientContext(spConnection))
			{
				// retrieve the SharePoint list and folder names for the doreplacedent location
				string listUrl, folderUrl;

				context.GetDoreplacedentLocationListAndFolder(location, out listUrl, out folderUrl);

				client.AddOrGetExistingFolder(listUrl, "{0}{1}/{2}".FormatWith(folderUrl, folderPath, name));
			}

			return result;
		}

19 View Source File : UserServiceExtensions.cs
License : MIT License
Project Creator : albyho

private static bool IsValidEmail(string source)
        {
            return Regex.IsMatch(source, @"^([\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?)$");
        }

19 View Source File : JsonValidatingReader.cs
License : MIT License
Project Creator : akaskela

private bool IsPropertyDefinied(JsonSchemaModel schema, string propertyName)
        {
            if (schema.Properties != null && schema.Properties.ContainsKey(propertyName))
            {
                return true;
            }

            if (schema.PatternProperties != null)
            {
                foreach (string pattern in schema.PatternProperties.Keys)
                {
                    if (Regex.IsMatch(propertyName, pattern))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

19 View Source File : LocalFileSystem.cs
License : MIT License
Project Creator : Adoxio

public IEnumerable<TemplateFileInfo> GetTemplateFiles()
		{
			var root = new DirectoryInfo(Root);

			if (!root.Exists)
			{
				return Enumerable.Empty<TemplateFileInfo>();
			}

			var rootUri = new Uri(
				root.FullName.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))
					? root.FullName
					: root.FullName + Path.DirectorySeparatorChar);

			return root.EnumerateFiles("*", SearchOption.AllDirectories)
				.Where(file => string.Equals(Path.GetExtension(file.Name), ".liquid", StringComparison.InvariantCulture) || string.Equals(Path.GetExtension(file.Name), ".json", StringComparison.InvariantCulture))
				.GroupBy(file => GetTemplateFileName(rootUri, file), e => e, StringComparer.InvariantCulture)
				.Where(e => Regex.IsMatch(e.Key, @"^[a-zA-Z0-9_\/]+$"))
				.Select(e => new TemplateFileInfo(e.Key, GetTemplateMetadata(e)));
		}

19 View Source File : UserServiceExtensions.cs
License : MIT License
Project Creator : albyho

private static bool IsValidUsername(string source)
        {
            return Regex.IsMatch(source, @"^([a-zA-Z][a-zA-Z0-9-_]*)$");
        }

19 View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099

public string GetMySqlEnumSetDefine() {
		if (fsql.Ado.DataType != FreeSql.DataType.MySql) return null;
		var sb = new StringBuilder();
		foreach (var col in table.Columns) {
			if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) {
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append("\r\n\t[Flags]");
				sb.Append($"\r\n\tpublic enum {this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}");
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append(" : long");
				sb.Append(" {\r\n\t\t");

				string slkdgjlksdjg = "";
				int field_idx = 0;
				int unknow_idx = 0;
				string exp2 = string.Concat(col.DbTypeTextFull);
				int quote_pos = -1;
				while (true) {
					int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
					if (quote_pos == -1) break;
					while (true) {
						quote_pos = exp2.IndexOf('\'', quote_pos + 1);
						if (quote_pos == -1) break;
						int r_cout = 0;
						//for (int p = 1; true; p++) {
						//	if (exp2[quote_pos - p] == '\\') r_cout++;
						//	else break;
						//}
						while (exp2[++quote_pos] == '\'') r_cout++;
						if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/) {
							string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 2).Replace("''", "'");
							if (Regex.IsMatch(str2, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$"))
								slkdgjlksdjg += ", " + str2;
							else
								slkdgjlksdjg += string.Format(@", 
/// <summary>
/// {0}
/// </summary>
[Description(""{0}"")]
Unknow{1}", str2.Replace("\"", "\\\""), ++unknow_idx);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
								slkdgjlksdjg += " = " + Math.Pow(2, field_idx++);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum && field_idx++ == 0)
								slkdgjlksdjg += " = 1";
							break;
						}
					}
					if (quote_pos == -1) break;
				}
				sb.Append(slkdgjlksdjg.Substring(2).TrimStart('\r', '\n', '\t'));
				sb.Append("\r\n\t}");
			}
		}
		return sb.ToString();
	}

19 View Source File : BuildProcessCallbacksHandler.cs
License : Apache License 2.0
Project Creator : Algoryx

private static void PostBuildExternal( string agxDynamicsPath,
                                           string agxPluginPath,
                                           FileInfo targetExecutableFileInfo,
                                           string targetDataPath )
    {
      // Finding loaded modules/binaries in current process located
      // in current environment AGX Dynamics directory. Additional
      // modules/binaries that are optional, i.e., possibly located
      // in another directory, are also included here.
      var loadedAgxModulesPaths = new List<string>();
      using ( new DynamicallyLoadedDependencies() ) {
        var process = Process.GetCurrentProcess();
        foreach ( ProcessModule module in process.Modules ) {
          if ( module.FileName.IndexOf( "[In Memory]" ) >= 0 )
            continue;

          var isMatch = module.FileName.IndexOf( agxDynamicsPath ) == 0 ||
                        IsOutOfInstallDependency( module.FileName );
          if ( isMatch )
            loadedAgxModulesPaths.Add( module.FileName );
        }
      }

      // Finding additional modules/binaries which an AGX Dynamics
      // runtime may depend on, e.g., vcruntimeIII.dll and msvcpIII.dll.
      var agxDepDir = AGXUnity.IO.Environment.Get( AGXUnity.IO.Environment.Variable.AGX_DEPENDENCIES_DIR );
      if ( !string.IsNullOrEmpty( agxDepDir ) ) {
        var agxDepDirInfo = new DirectoryInfo( agxDepDir );
        foreach ( var file in agxDepDirInfo.EnumerateFiles( "*.dll", SearchOption.AllDirectories ) ) {
          foreach ( var dependency in m_additionalDependencies )
            if ( System.Text.RegularExpressions.Regex.IsMatch( file.Name, dependency ) )
              loadedAgxModulesPaths.Add( file.FullName );
        }
      }

      if ( loadedAgxModulesPaths.Count == 0 ) {
        Debug.LogWarning( GUI.AddColorTag( "Copy AGX Dynamics binaries - no binaries found in current process.", Color.red ) );
        return;
      }

      // dllTargetPath: ./<name>_Data/Plugins
      var dllTargetPath = AGXUnity.IO.Environment.GetPlayerPluginPath( targetDataPath );
      if ( !Directory.Exists( dllTargetPath ) )
        Directory.CreateDirectory( dllTargetPath );

      // agxRuntimeDataPath: ./<name>_Data/Plugins/agx
      var agxRuntimeDataPath = AGXUnity.IO.Environment.GetPlayerAGXRuntimePath( targetDataPath );
      if ( !Directory.Exists( agxRuntimeDataPath ) )
        Directory.CreateDirectory( agxRuntimeDataPath );

      Debug.Log( "Copying Components to: " + GUI.AddColorTag( agxRuntimeDataPath + Path.DirectorySeparatorChar + "Components", Color.green ) );
      CopyDirectory( new DirectoryInfo( agxPluginPath + Path.DirectorySeparatorChar + "Components" ),
                     new DirectoryInfo( agxRuntimeDataPath + Path.DirectorySeparatorChar + "Components" ) );

      var targetDataDir = agxRuntimeDataPath + Path.DirectorySeparatorChar + "data";
      Debug.Log( "Copying data to: " + GUI.AddColorTag( targetDataDir, Color.green ) );
      if ( !Directory.Exists( targetDataDir ) )
        Directory.CreateDirectory( targetDataDir );
      CopyDirectory( new DirectoryInfo( agxDynamicsPath + Path.DirectorySeparatorChar + "data" + Path.DirectorySeparatorChar + "TerrainMaterials" ),
                     new DirectoryInfo( targetDataDir + Path.DirectorySeparatorChar + "TerrainMaterials" ) );

      foreach ( var modulePath in loadedAgxModulesPaths ) {
        var moduleFileInfo = new FileInfo( modulePath );
        try {
          moduleFileInfo.CopyTo( dllTargetPath + Path.DirectorySeparatorChar + moduleFileInfo.Name, true );
          string additionalInfo = "";
          if ( IsOutOfInstallDependency( modulePath ) )
            additionalInfo = GUI.AddColorTag( $" ({modulePath})", Color.yellow );
          Debug.Log( "Successfully copied: " +
                     GUI.AddColorTag( dllTargetPath + Path.DirectorySeparatorChar, Color.green ) +
                     GUI.AddColorTag( moduleFileInfo.Name, Color.Lerp( Color.blue, Color.white, 0.75f ) ) +
                     additionalInfo );
        }
        catch ( Exception e ) {
          Debug.Log( "Failed copying: " +
                     GUI.AddColorTag( dllTargetPath + Path.DirectorySeparatorChar, Color.red ) +
                     GUI.AddColorTag( moduleFileInfo.Name, Color.red ) +
                     ": " + e.Message );
        }
      }

      CheckGenerateEncryptedRuntime( targetExecutableFileInfo );
    }

19 View Source File : Expression.cs
License : MIT License
Project Creator : Adoxio

private static Expression GetExpression(string op, string name, List<Expression> operands, Func<string, string, object> parseValue)
		{
			// check if this is a logical expression

			if (op == "&")
			{
				if (operands == null || operands.Count == 0)
				{
					throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
				}

				return And(operands.ToArray());
			}
			if (op == "|")
			{
				if (operands == null || operands.Count == 0)
				{
					throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
				}

				return Or(operands.ToArray());
			}
			if (op == "!")
			{
				if (operands == null || operands.Count != 1)
				{
					throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
				}

				return Not(operands[0]);
			}
			if (op == null)
			{
				if (operands == null || operands.Count != 1)
				{
					throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
				}

				return NoOp(operands[0]);
			}
			// check if this is a conditional string

			var ops = name.Split(new[] { op }, 2, StringSplitOptions.None);

			if (ops.Length != 2)
			{
				throw new InvalidExpressionException(string.Format("Invalid expression {0}.", name));
			}

			var attributeName = ops[0];
			var text = ops[1];
			var containsWildcard = text != null && (Regex.IsMatch(text, @"[^\\]\*") || text.StartsWith("*"));

			var value = parseValue(attributeName, text);

			// if an '*' is detected in an '=' expression, promote to 'like' expression
			if ((op == "=" || op == "==") && containsWildcard)
			{
				op = "~=";
			}

			if (op == "=" || op == "==")
			{
				return Equals(attributeName, value);
			}
			if (op == "!=")
			{
				if (containsWildcard)
				{
					// if an '*' is detected in an '=' expression, promote to 'like' expression
					return NotLike(attributeName, value);
				}
				return NotEquals(attributeName, value);
			}
			if (op == "~=")
			{
				return Like(attributeName, value);
			}
			if (op == "<")
			{
				return LessThan(attributeName, value);
			}
			if (op == "<=")
			{
				return LessThanOrEquals(attributeName, value);
			}
			if (op == ">")
			{
				return GreaterThan(attributeName, value);
			}
			if (op == ">=")
			{
				return GreaterThanOrEquals(attributeName, value);
			}

			throw new InvalidOperationException(string.Format("Unknown operator symbol {0}.", op));
		}

19 View Source File : RegexTextBoxBehavior.cs
License : MIT License
Project Creator : aliprogrammer69

private void OnPreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e) {
            string text = string.Concat(replacedociatedObject.Text, e.Text);
            e.Handled = !Regex.IsMatch(text, Expersion);
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n

private string Handle_Payload()
        {
            //对用户输入的payload进行一些转换处理,方便下一步的加密
            string raw_input = textBox1.Text.Trim().Replace("\r\n", "").Replace("\n", "").Replace("\r", ""); //支持多种linux win换行符
            string payload_pattern_csharp = @"\{(.+?)\}";
            string payload_pattern_c = @"=.*"";$";
            string[] raw_payload_array;
            if (Regex.IsMatch(raw_input, payload_pattern_c))
            {
                //c语言格式的shellcode,转成 csharp 格式
                raw_input = raw_input.Replace("\"", "").Replace("\\", ",0").Replace(";", "").Replace("=", "{").Replace("{,", "{ ") + " }";
            }
            string raw_payload = Regex.Matches(raw_input, payload_pattern_csharp)[0].Value.Replace("{", "").Replace("}", "").Trim();
            raw_payload = raw_payload.TrimStart(',');
            raw_payload_array = raw_payload.Split(',');
            List<byte> byte_payload_list = new List<byte>();

            foreach (string i in raw_payload_array)
            {
                byte_payload_list.Add(string_to_int(i));
            }
            byte[] payload_result = byte_payload_list.ToArray();

            //加密payload并转换为字符串,准备写入文件
            byte[] encrypted_payload = Encrypter.Encrypt(KEY, payload_result);
            string string_encrypted_payload = string.Join(",", encrypted_payload);
            //MessageBox.Show(string_encrypted_payload);
            return string_encrypted_payload;
        }

19 View Source File : LoginViewModel.cs
License : MIT License
Project Creator : aliprogrammer69

public bool CanLogin() =>
            !string.IsNullOrEmpty(_phoneNumber) &&
            !ShowProgress &&
            Regex.IsMatch(_phoneNumber, @"^\s*\+?\s*([0-9][\s-]*){9,}$");

19 View Source File : EmbeddedResourceAssemblyAttribute.cs
License : MIT License
Project Creator : Adoxio

private static string ConvertDirectoryToResourceName(string directory)
		{
			// converting and individual directory
			// for all parts: prepend an '_' if the name starts with a numeric character
			// convert '-' to '_'

			var parts = directory.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

			if (parts.Any())
			{
				var partsWithUnderscores = parts.Select(p => Regex.IsMatch(p, @"^\d") ? "_" + p : p);
				return string.Join(".", partsWithUnderscores.ToArray()).Replace('-', '_');
			}

			return null;
		}

19 View Source File : GridifyMapper.cs
License : MIT License
Project Creator : alirezanet

public IGridifyMapper<T> AddMap(string from, Expression<Func<T, object?>> to, Func<string, object>? convertor = null!,
         bool overrideIfExists = true)
      {
         if (!overrideIfExists && HasMap(from))
            throw new GridifyMapperException($"Duplicate Key. the '{from}' key already exists");

         RemoveMap(from);
         var isNested = Regex.IsMatch(to.ToString(), @"\.Select\s*\(");
         _mappings.Add(new GMap<T>(from, to, convertor, isNested));
         return this;
      }

19 View Source File : MixedRealityToolkitFiles.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static bool IsSentinelFile(string replacedetPath)
        {
            return Regex.IsMatch(Path.GetFileName(replacedetPath), SentinelFilePattern);
        }

19 View Source File : MemoryCache.cs
License : MIT License
Project Creator : alonsoalon

public async Task<long> RemoveByPatternAsync(string pattern)
        {
            if (pattern.IsNull())
                return default;

            pattern = Regex.Replace(pattern, @"\{.*\}", "(.*)");

            var keys = GetAllKeys().Where(k => Regex.IsMatch(k, pattern));

            if (keys != null && keys.Count() > 0)
            {
                return await RemoveAsync(keys.ToArray());
            }

            return default;
        }

19 View Source File : StringUtilities.cs
License : MIT License
Project Creator : AdrianWilczynski

public static bool HasInterfacePrefix(this string text)
            => Regex.IsMatch(text, InterfacePrefixRegex);

19 View Source File : StringExtension.cs
License : MIT License
Project Creator : AlphaYu

public static bool IsLike([NotNull] this string @this, string pattern)
        {
            // Turn the pattern into regex pattern, and match the whole string with ^$
            var regexPattern = "^" + Regex.Escape(pattern) + "$";

            // Escape special character ?, #, *, [], and [!]
            regexPattern = regexPattern.Replace(@"\[!", "[^")
                .Replace(@"\[", "[")
                .Replace(@"\]", "]")
                .Replace(@"\?", ".")
                .Replace(@"\*", ".*")
                .Replace(@"\#", @"\d");

            return Regex.IsMatch(@this, regexPattern);
        }

19 View Source File : XmlCommandsProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

public void Load(System.Reflection.replacedembly replacedembly, string pattern)
        {
            var filenames = replacedembly.GetManifestResourceNames();
            foreach (var item in filenames)
            {
                if (!Regex.IsMatch(item, pattern))
                {
                    continue;
                }
                Load(replacedembly.GetManifestResourceStream(item));
            }
        }

19 View Source File : LanguageHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

public static bool IsTwoLetters(string language)
        {
            if (language == null)
            {
                return false;
            }

            return Regex.IsMatch(language, "^[A-Za-z]{2}$");
        }

19 View Source File : RatingBar.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private bool IsInt(object value)
      {
         if (Regex.IsMatch(value.ToString(), "^\\d+$"))
         {
            return true;
         }
         else
         {
            return false;
         }
      }

19 View Source File : EmailService.cs
License : MIT License
Project Creator : ADefWebserver

public static bool IsHTMLMail(string Body)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(Body, "<[^>]*>");
        }

19 View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744

private Dictionary<string, string> Factorization(string expression)
        {
            var experssions = new Dictionary<string, string>();
            var pattern = @"\([^\(\)]+\)";
            var text = $"({expression})";
            while (Regex.IsMatch(text, pattern))
            {
                var key = $"${experssions.Count}";
                var value = Regex.Match(text, pattern).Value;
                experssions.Add(key, value);
                text = text.Replace(value, key);
            }
            return experssions;
        }

19 View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744

private Expression ResovleConstantExpression(string expression)
        {
            //自动类型推断生成表达式
            if (expression.StartsWith("'") && expression.EndsWith("'"))
            {
                //字符串常量
                return Expression.Constant(expression.Trim('\''), typeof(string));
            }
            else if (expression == "true" || expression == "false")
            {
                return Expression.Constant(expression, typeof(bool));
            }
            else if (Regex.IsMatch(expression, @"^\d+$"))
            {
                //int类型常量
                return Expression.Constant(expression, typeof(int));
            }
            else if (Regex.IsMatch(expression, @"^\d*\.\d*$"))
            {
                //double
                return Expression.Constant(expression, typeof(int));
            }
            else if (expression == "null")
            {
                return Expression.Constant(null, typeof(object));
            }
            return Expression.Constant(expression, typeof(object));
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : 2dust

void AppendText(string text)
        {
            if (this.txtMsgBox.InvokeRequired)
            {
                Invoke(new AppendTextDelegate(AppendText), new object[] { text });
            }
            else
            {
                if (!Utils.IsNullOrEmpty(MsgFilter))
                {
                    if (!Regex.IsMatch(text, MsgFilter))
                    {
                        return;
                    }
                }
                //this.txtMsgBox.AppendText(text);
                ShowMsg(text);
            }
        }

19 View Source File : EmbeddedResourceFileSystem.cs
License : MIT License
Project Creator : Adoxio

private bool TryGetFullPath(string templatePath, out string fullPath)
		{
			fullPath = null;

			if (templatePath == null || !Regex.IsMatch(templatePath, @"^[a-zA-Z0-9_][a-zA-Z0-9_\/]*$"))
			{
				return false;
			}

			try
			{
				var basePath = templatePath.Contains("/")
					? Path.Combine(Root, Path.GetDirectoryName(templatePath))
					: Root;

				var fileName = "{0}.liquid".FormatWith(Path.GetFileName(templatePath));

				fullPath = Regex.Replace(Path.Combine(basePath, fileName), @"\\|/", ".");

				return true;
			}
			catch (System.ArgumentException)
			{
				return false;
			}
		}

19 View Source File : QueryEngine.cs
License : Apache License 2.0
Project Creator : alaatm

public static string Translate(string filter, string[] nonPropertyColumns)
        {
            // If enclosed in quotes then treat as a search string
            if (filter[0] == '"' && filter[filter.Length - 1] == '"')
            {
                return string.Format("(message LIKE '%{0}%' OR exception LIKE '%{0}%' OR id in (SELECT logId FROM log_property WHERE value LIKE '%{0}%'))", filter.Substring(1, filter.Length - 2).Replace("'", "''"));
            }

            // If has no whitespace, "=", "!", "(", ")" then treat as a search string
            if (!Regex.IsMatch(filter, @"\s|=|!|\(|\)"))
            {
                return string.Format("(message LIKE '%{0}%' OR exception LIKE '%{0}%' OR id in (SELECT logId FROM log_property WHERE value LIKE '%{0}%'))", filter.Replace("'", "''"));
            }

            var scanner = new Scanner(filter);
            var tokens = scanner.Scan();

            return new CodeGenerator().Generate(new Parser(tokens, nonPropertyColumns).Parse());
        }

See More Examples