C# (CSharp) Class System.Text.RegularExpressions. Regex Code Examples

C# (CSharp) System.Text.RegularExpressions.Regex - 30 examples found. These are the top rated real world C# (CSharp) examples of class System.Text.RegularExpressions.Regex extracted from open source projects. You can rate examples to help us improve the quality of examples
Inheritance: ISerializable
Example #1
0
 public void ShouldRegexMatchColonTerminatedFirstMultilineSlashNTerminated()
 {
   string content = string.Format("blah:{0}blah", "\n");
   Regex regex = new Regex(".*:$", RegexOptions.Multiline);
   regex.IsMatch(content).Should().BeTrue();
   regex.Matches(content).Count.Should().Be(1);
 }
Example #2
0
 public MessInfo(string s)
 {
     const string FILE = "file";
     const string LINE = "line";
     const string COND = "cond";
     const string ERROR = "error";
     const string MESSAGE = "message";
     Regex rex = new Regex(@"""?(?<" + FILE + @">[a-zA-Z]:\\(?:[^\\/:*?<>|\r\n]+\\)*(?:[^\\/:*?""<>|\r\n]+))""?,\sline\s(?<" + LINE + @">[0-9]+):\s(?<" + COND + @">Error|Warning):[^#]+#(?<"+ERROR+@">[0-9]+(?:-\D)?):\s*(?<"+MESSAGE+@">.+)\z");
     Match m = rex.Match(s);
     if (m.Success)
     {
         try
         {
             this.File = m.Groups[FILE].Value;
             this.Line = int.Parse(m.Groups[LINE].Value);
             this.Cond = (Level)Enum.Parse(typeof(Level), m.Groups[COND].Value);
             this.Error = m.Groups[ERROR].Value;
             this.Message = m.Groups[MESSAGE].Value;
             this.Success = true;
         }
         catch
         {
             this.Success = false;
         }
     }
 }
        /// <summary>
        /// Corrects the image path relative to the requested page or css where they originate from
        /// </summary>
        /// <param name="url"></param>
        /// <param name="requestPath"></param>
        /// <returns></returns>
        public static string CorrectUrl(string url, string requestPath)
        {
            var correctedImgPath = url.TrimStart('~');

            // make sure 'requestPath' starts with a '/'
            if (!requestPath.StartsWith("/"))
                requestPath = "/" + requestPath;

            if (!url.StartsWith("/") && !url.StartsWith("../"))
            {
                correctedImgPath = VirtualPathUtility.GetDirectory(requestPath) + url.TrimStart('/');
            }
            else if (url.StartsWith("../"))
            {
                var path = VirtualPathUtility.GetDirectory(requestPath);
                var regex = new Regex(@"\.\./");
                var levelUpMatches = regex.Matches(url);
                var numberOfLevelsUp = levelUpMatches.Count;
                var pathDirs = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                var newPathDirs = pathDirs.Take(pathDirs.Length - numberOfLevelsUp);
                var newPath = String.Join("/", newPathDirs).Trim();
                correctedImgPath = regex.Replace(url, "");
                correctedImgPath = String.IsNullOrEmpty(newPath) ? String.Format("/{0}", correctedImgPath) : String.Format("/{0}/{1}", newPath, correctedImgPath);
            }

            return correctedImgPath;
        }
Example #4
0
		public static string UpdateStatus(string status, TwUser user, string replyId)
		{
			Regex regex = new Regex(@"\[(.*?)\]");
			List<FileInfo> media = new List<FileInfo>();
			foreach (System.Text.RegularExpressions.Match match in regex.Matches(status))
			{
				status = status.Replace(match.Value, "");
				FileInfo file = new FileInfo(match.Value.Replace("[", "").Replace("]", ""));
				if (!file.Exists)
					throw new FileNotFoundException("File not found", file.FullName);
				media.Add(file);
            }

			if (media.Count > 4) //limited by the twitter API
				throw new ArgumentOutOfRangeException("media", "Up to 4 media files are allowed per tweet");

			if (user == null)
				user = TwUser.LoadCredentials();
			string encodedStatus = Util.EncodeString(status);
			
			if (media.Count == 0)
				return InternalUpdateStatus(user, encodedStatus, replyId);
			else
				return InternalUpdateWithMedia(user, encodedStatus, replyId, media);
		}
        /// <summary>
        /// Gets inner HTML string from the first found element with the given class name (e.g. class="sample-test").
        /// </summary>
        /// <param name="sourceString">An HTML string to parse.</param>
        /// <param name="className">Class name.</param>
        /// <returns>An HTML string.</returns>
        public static string getInnerHTML(string sourceString, string className)
        {
            Match match = new Regex(className).Match(sourceString);

            if (!match.Success) return "";

            int lb = match.Index + className.Length;
            for (; lb < sourceString.Length && !(sourceString[lb - 1] == '>' && sourceString[lb - 2] != '\\'); lb++);
            int rb = lb, tmp, bracketCounter = 1;

            while (bracketCounter > 0)
            {
                while (rb < sourceString.Length && !(sourceString[rb] == '<' && sourceString[rb - 1] != '\\')) rb++;

                tmp = rb + 1;
                while (tmp < sourceString.Length && !(sourceString[tmp] == '>' && sourceString[tmp - 1] != '\\')) tmp++;

                if (sourceString[rb + 1] == '/') bracketCounter--;
                else if (sourceString[tmp - 1] != '/') bracketCounter++;

                rb++;
            }

            while (!(sourceString[--rb] == '<' && sourceString[rb - 1] != '\\')) ;

            return sourceString.Substring(lb, rb - lb);
        }
        public override void DataSet(string myPath, string myPattern)
        {
            string[] fileList = Directory.GetFiles(myPath, myPattern, SearchOption.AllDirectories);

            Regex regexMov = new Regex(MovieContents.REGEX_MOVIE_EXTENTION, RegexOptions.IgnoreCase);
            Regex regexJpg = new Regex(@".*\.jpg$|.*\.jpeg$", RegexOptions.IgnoreCase);
            Regex regexLst = new Regex(@".*\.wpl$|.*\.asx$", RegexOptions.IgnoreCase);

            foreach (string file in fileList)
            {
                listFileInfo.Add(new common.FileContents(file, myPath));

                if (regexMov.IsMatch(file))
                    MovieCount++;
                if (regexJpg.IsMatch(file))
                    ImageCount++;
                if (regexLst.IsMatch(file))
                    ListCount++;

                if (regexJpg.IsMatch(file) && ImageCount == 1)
                    StartImagePathname = file;
            }
            ColViewListFileInfo = CollectionViewSource.GetDefaultView(listFileInfo);

            if (ColViewListFileInfo != null && ColViewListFileInfo.CanSort == true)
            {
                ColViewListFileInfo.SortDescriptions.Clear();
                ColViewListFileInfo.SortDescriptions.Add(new SortDescription("FileInfo.LastWriteTime", ListSortDirection.Ascending));
            }
        }
Example #7
0
        private void ValidateInputText()
        {
            if (regexPattern == String.Empty)
            {
                Message = "Regex is Empty";
                return;
            }

            try
            {
                regex = new Regex(regexPattern);
                Message = String.Empty;
            }
            catch (ArgumentException error)
            {
                Message = error.Message;
                return;
            }

            if (InputText != null)
            {
                bool isMatch = regex.IsMatch(InputText);
                if (isMatch)
                {
                    Message = "It's works!";
                }
                else
                {
                    Message = "No working :(";
                }
            }
        }
Example #8
0
        /// <summary/>
        protected CodeFormat()
        {
            //generate the keyword and preprocessor regexes from the keyword lists
            var r = new Regex(@"\w+|-\w+|#\w+|@@\w+|#(?:\\(?:s|w)(?:\*|\+)?\w+)+|@\\w\*+");
            string regKeyword = r.Replace(Keywords, @"(?<=^|\W)$0(?=\W)");
            string regPreproc = r.Replace(Preprocessors, @"(?<=^|\s)$0(?=\s|$)");
            r = new Regex(@" +");
            regKeyword = r.Replace(regKeyword, @"|");
            regPreproc = r.Replace(regPreproc, @"|");

            if (regPreproc.Length == 0)
            {
                regPreproc = "(?!.*)_{37}(?<!.*)"; //use something quite impossible...
            }

            //build a master regex with capturing groups
            var regAll = new StringBuilder();
            regAll.Append("(");
            regAll.Append(CommentRegex);
            regAll.Append(")|(");
            regAll.Append(StringRegex);
            if (regPreproc.Length > 0)
            {
                regAll.Append(")|(");
                regAll.Append(regPreproc);
            }
            regAll.Append(")|(");
            regAll.Append(regKeyword);
            regAll.Append(")");

            RegexOptions caseInsensitive = CaseSensitive ? 0 : RegexOptions.IgnoreCase;
            CodeRegex = new Regex(regAll.ToString(), RegexOptions.Singleline | caseInsensitive);
        }
Example #9
0
        public void ExecuteMethodFromRegex(IrcEventArgs e)
        {
            if(isRunning==true)
            {
                SendUnscramble(e);
            }
            foreach(KeyValuePair<string,string> pair in regexDictionary)
            {
                regex = new Regex(pair.Key);
                if(regex.IsMatch(e.Data.Message))
                {
                    string methodName = pair.Value;

                        //Get the method information using the method info class
                        MethodInfo mi = this.GetType().GetMethod(methodName);
                        object[] objargs = new object[1];
                        objargs[0]=e;
            //						//Invoke the method
            //						// (null- no paramyeseter for the method call
            //						// or you can pass the array of parameters...)
                    if(mi==null)
                    {
                        //client.SendMessage(SendType.Message, e.Data.Channel,"mi is null! "+e.Data.Message);
                        SharpBotClient.SharpBotClient.SendChannelMessag(e.Data.Channel,"handled from client");
                    }
                    else
                    {
                        mi.Invoke(this,objargs);
                    }

                }
            }
        }
        /// <summary>
        /// Обрабатывает шаблон, вставляет значение полей моделей в макросы в шаблоне
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        protected override string Process(string content)
        {
            // Подгатавливаем данные
            var parseRegEx = new Regex(@"\$\{([A-Za-z0-9]+?)\}");
            var sb = new StringBuilder(content);

            var ti = Model.GetType();

            // Находим все вхождения макросов по регулярному выражению
            var matches = parseRegEx.Matches(content);
            foreach (Match match in matches)
            {
                var propertyName = match.Groups[1].Value;

                // Ищем свойство у модели
                var propertyInfo = ti.GetProperty(propertyName);
                if (propertyInfo == null)
                {
                    // Похоже что данное свойство у модели не найдено
                    continue;
                }
                var value = propertyInfo.GetValue(Model,null);

                // Выполняем замену
                sb.Replace(match.Value, value != null ? value.ToString() : String.Empty);
            }

            // Отдаем преобразованный результат
            return sb.ToString();
        }
Example #11
0
 public int RowCount(string source)
 {
   Regex rowRegex = new Regex(_rowDelimiter);
   _source = source;
   _rows = rowRegex.Matches(_source);
   return _rows.Count;
 }
        public override IEnumerable<IVertex> GetMatchingVertices(IVertexType myInterestingVertexType)
        {
            Regex regexpression;

            try
            {
                regexpression = new Regex((String)_constant.Value);
            }
            catch (Exception e)
            {
                throw new InvalidLikeOperationException(String.Format("Invalid regular expression given:{0}{1}", Environment.NewLine, e.Message), e);
            }

            foreach (var aVertex in _vertexStore.GetVerticesByTypeID(_securityToken, _transactionToken, myInterestingVertexType.ID, _property.Edition, VertexRevisionFilter))
            {
                var value = _property.Property.GetValue(aVertex);

                if (value != null && (regexpression.IsMatch((String)value)))
                {
                    yield return aVertex;
                }
            }

            yield break;
        }
 private IEnumerable<string> LoadProjects(
     string solutionPath)
 {
     const string projectRegEx = "Project\\(\"\\{[\\w-]*\\}\"\\) = \"([\\w _]*.*)\", \"(.*\\.(cs|vcx|vb)proj)\"";
     var content = File.ReadAllText(solutionPath);
     var projReg = new Regex(projectRegEx, RegexOptions.Compiled);
     var matches = projReg.Matches(content).Cast<Match>();
     var projects = matches.Select(x => x.Groups[2].Value).ToList();
     for (var i = 0; i < projects.Count; ++i)
     {
         if (!Path.IsPathRooted(projects[i]))
         {
             var folderName = Path.GetDirectoryName(solutionPath);
             if (folderName != null)
                 projects[i] = Path.Combine(folderName, projects[i]);
         }
         try
         {
             projects[i] = Path.GetFullPath(projects[i]);
         }
         catch (NotSupportedException ex)
         {
             resolver_ProgressMessageEvent($"Path: {projects[i]}, Error: {ex.Message}");
         }
     }
     return projects;
 }
Example #14
0
 public TypePattern()
 {
     IPattern descritePattern = PatternFactory.GetInstance().Get(typeof (DiscreteTypePattern));
     IPattern compositePattern = PatternFactory.GetInstance().Get(typeof (CompositeTypePattern));
     m_TextPattern = "(" + descritePattern.TextPattern + "|" + compositePattern.TextPattern + ")";
     m_Regex = new Regex(m_TextPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
 }
Example #15
0
        public FlexibleFloat(string value)
        {
            // Variables
            Regex	re=	new Regex(@"([0-9]+)(px|%||em|ex|ch|rem|vw|cm|mm|inches|pt|pc)");
            string[]	splits=	re.Replace(value.Trim(), "$1 $2").Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            val=	float.Parse(splits[0]);
            switch(splits[1])
            {
                case "px":	unitType=	FlexFloatType.px;	break;
                case "%":	unitType=	FlexFloatType.percentage;	break;
                case "em":	unitType=	FlexFloatType.em;	break;
                case "ex":	unitType=	FlexFloatType.ex;	break;
                case "ch":	unitType=	FlexFloatType.ch;	break;
                case "rem":	unitType=	FlexFloatType.rem;	break;
                case "vw":	unitType=	FlexFloatType.vw;	break;
                case "vh":	unitType=	FlexFloatType.vh;	break;
                case "cm":	unitType=	FlexFloatType.cm;	break;
                case "mm":	unitType=	FlexFloatType.mm;	break;
                case "inches":	unitType=	FlexFloatType.inches;	break;
                case "pt":	unitType=	FlexFloatType.pt;	break;
                case "pc":	unitType=	FlexFloatType.pc;	break;
                default:	unitType=	FlexFloatType.px;	break;
            }
        }
Example #16
0
        private string CheckMetaCharSetAndReEncode(Stream memStream, string html)
        {
            Match m = new Regex(@"<meta\s+.*?charset\s*=\s*(?<charset>[A-Za-z0-9_-]+)", RegexOptions.Singleline | RegexOptions.IgnoreCase).Match(html);
            if (m.Success)
            {
                string charset = m.Groups["charset"].Value.ToLower() ?? "iso-8859-1";
                if ((charset == "unicode") || (charset == "utf-16"))
                {
                    charset = "utf-8";
                }

                try
                {
                    Encoding metaEncoding = Encoding.GetEncoding(charset);
                    if (Encoding != metaEncoding)
                    {
                        memStream.Position = 0L;
                        StreamReader recodeReader = new StreamReader(memStream, metaEncoding);
                        html = recodeReader.ReadToEnd().Trim();
                        recodeReader.Close();
                    }
                }
                catch (ArgumentException)
                {
                }
            }

            return html;
        }
Example #17
0
        public void TestPromotionForStorage()
        {
            string test
                = @"integer g() { return 0; }
                    f() { 
                        integer i;
                        float f = 1;
                        float h = g();
                        float j = i;
                        float l = i++;
                        float k = i - 5;

                        f = 1;
                        h = g();
                        j = i;
                        l = i++;
                        k = i - 5;
                    }

                    default { state_entry() {} }
                    ";

            TestListener listener = new TestListener();
            MCompilerFrontend testFrontend = new MCompilerFrontend(listener, "..\\..\\..\\..\\grammar", true);
            CompiledScript script = testFrontend.Compile(test);

            string byteCode = testFrontend.GeneratedByteCode;
            Console.WriteLine(byteCode);
            int castCount = new Regex("fcast").Matches(byteCode).Count;

            Assert.IsTrue(listener.HasErrors() == false);
            Assert.AreEqual(castCount, 10);
        }
        public static List<Category> GetBoards(this string url)
        {
            var temp = new List<Category>();

            if (url.Contains("collection"))
            {
                temp.Add(Category.General);
                temp.Add(Category.Manga);
                temp.Add(Category.HighRes);
                return temp;
            }

            var board = new Regex("(board=[0-9]{0,3})");
            var boardMatch = board.Match(url);
            var boards = Regex.Replace(boardMatch.Value, "[^0-9]+", string.Empty);

            if (boards.Contains("2"))
                temp.Add(Category.General);
            if (boards.Contains("1"))
                temp.Add(Category.Manga);
            if (boards.Contains("3"))
                temp.Add(Category.HighRes);

            return temp;
        }
        private void tb_humidity_input_TextChanged(object sender, EventArgs e)
        {
            if(tb_humidity_input.Text != "") {
            string pattern = @"^[0-9]*(?:\.[0-9]*)?$";//@"^[0 - 9]([.][0 - 9])?$"; //@"^[0-9]+$"; //for integers only
            Regex rgx = new Regex(pattern);
            string text = tb_humidity_input.Text;
            //string sentence = "Who writes these notes?";
            if (rgx.IsMatch(text) == true)
            {
                //matched no need to edit
                double x = double.Parse(tb_humidity_input.Text);
                if (x >= 0 && x <= 100)
                {

                }
                else
                {
                    //show error message.
                    MessageBox.Show("Value out of range");
                    tb_humidity_input.Text = 0.ToString();
                }
            }
            else
            {
                MessageBox.Show("You can only input integer values between 0-100%");
                // dataGridView1.CurrentCell.Value = initialNodeSize;
                tb_humidity_input.Text = 0.ToString();
            }

            }
            else
            {
                tb_humidity_input.Text = 0.ToString();
            }
        }
        public static int GetThpp(this string str)
        {
            var numReg = new Regex("thpp=([0-9]{0,9})");
            var numMatch = numReg.Match(str);

            return Convert.ToInt32(numMatch.Groups[1].ToString());
        }
        public JobDefinition ParseJIL(TextReader instr)
        {
            JobDefinition jobdef = new JobDefinition();

            char[] delim = {':'};
            string [] keyval = new string[2];
            string jil;

            Regex rx = new Regex("[A-Za-z-_]+:.*"); // Looks like a JIL key/value pair

            while ( (jil = instr.ReadLine()) != null )
            {
                if (rx.IsMatch(jil))
                {
                    keyval = jil.Split(delim, 2);
                    jobdef.SetField(keyval[0], keyval[1]);
                }
                else
                {
                    Console.Error.WriteLine("Warning: Malformed JIL encountered and ignored: {0}", jil);
                }
            }

            return jobdef;
        }
Example #22
0
        public static string ToWords(this string s)
        {
            if (!s.HasValue()) return s;

            var regex = new Regex("(?<=[a-z])(?<x>[A-Z0-9])|(?<=.)(?<x>[A-Z0-9])(?=[a-z])");
            return regex.Replace(s, " ${x}");
        }
Example #23
0
        public List<ESPNGame> GetGames(int year, int seasonType, int weekNum)
        {
            var games = new List<ESPNGame>();
            Regex gameRX = new Regex("gameId=[0-9]+");
            var url = string.Format("{0}/{1}", GAME_URL, string.Format("_/year/{0}/seasontype/{1}/week/{2}", year.ToString(), seasonType.ToString(), weekNum.ToString()));
            var html = HelperMethods.LoadHtmlFromUrl(url);
            var gameIds = gameRX.Matches(html);

            foreach (Match gId in gameIds)
            {
                var gameId = System.Convert.ToInt32(gId.Value.Replace("gameId=", string.Empty));

                if (!games.Select(g => g.GameId).Contains(gameId))
                {
                    try
                    {
                        var teamsForGame = GetTeamsByGame(gameId);

                        ESPNGame game = new ESPNGame();
                        game.GameId = gameId;
                        game.HomeTeamId = teamsForGame["home"];
                        game.AwayTeamId = teamsForGame["away"];
                        games.Add(game);
                    }
                    catch { }
                }
            }

            return games.Distinct().ToList();
        }
		public static string RefreshMacros(this string sourceText, string macrosName, string macrosCode) {

			var vars = MacrosTemplates.GetParameters(sourceText, macrosName);
			var rawArgs = MacrosTemplates.GetPartOfMacros(sourceText, macrosName, "macrosArgs");

			var macrosText = macrosTemplate.Replace("{{NAME}}", macrosName);
			macrosText = macrosText.Replace("{{CODE}}", macrosCode);

			Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
			var match = rgx.Match(sourceText);
			var spaces = match.Groups[1].Value;

			macrosText = macrosText.Replace(Environment.NewLine, Environment.NewLine + spaces);

			var pt = @"(\s?)#region\s+macros\s+" + macrosName + "\\s+(.*?)#endregion";

			rgx = new Regex(pt, RegexOptions.IgnoreCase | RegexOptions.Singleline);
			//Debug.Log(macrosName + ": " + sourceText + " => " + macrosText);
			sourceText = rgx.Replace(sourceText, spaces + macrosText);

			foreach (var item in vars) {
				
				sourceText = sourceText.Replace("/*{" + item.Key + "}*/", item.Value);
				sourceText = sourceText.Replace("{" + item.Key + "}", item.Value);

			}

			sourceText = sourceText.Replace(macrosName, macrosName + " " + rawArgs);

			return sourceText;

		}
        /// <summary>
        /// Gets a list of inner HTML strings from all elements with the given class name (e.g. class="sample-test").
        /// </summary>
        /// <param name="sourceString">An HTML string to parse.</param>
        /// <param name="className">Class name.</param>
        /// <returns>An HTML string.</returns>
        public static List<string> getInnerHTMLList(string sourceString, string className)
        {
            List<string> result = new List<string>();

            MatchCollection matches = new Regex(className).Matches(sourceString);
            int lb, rb, tmp = 0, bracketCounter;
            foreach (Match match in matches)
            {
                lb = match.Index + className.Length;
                if (lb <= tmp) continue;
                for (; lb < sourceString.Length && !(sourceString[lb - 1] == '>' && sourceString[lb - 2] != '\\'); lb++) ;
                rb = lb;
                bracketCounter = 1;

                while (bracketCounter > 0)
                {
                    while (rb < sourceString.Length && !(sourceString[rb] == '<' && sourceString[rb - 1] != '\\')) rb++;

                    tmp = rb + 1;
                    while (tmp < sourceString.Length && !(sourceString[tmp] == '>' && sourceString[tmp - 1] != '\\')) tmp++;

                    if (sourceString[rb + 1] == '/') bracketCounter--;
                    else if (sourceString[tmp - 1] != '/') bracketCounter++;

                    rb++;
                }

                while (!(sourceString[--rb] == '<' && sourceString[rb - 1] != '\\')) ;
                result.Add(sourceString.Substring(lb, rb - lb));
            }

            return result;
        }
Example #26
0
 private static int GetSumOfInts(string input)
 {
     var regex = new Regex(@"(-?\d+)");
     var matches = regex.Matches(input).OfType<Match>().ToList();
     var sum = matches.Sum(x => int.Parse(x.Value));
     return sum;
 }
Example #27
0
        private void SizeValidation(object sender, CancelEventArgs e)
        {
            if (!(sender is TextBox)) { return; }

            Regex sizeReg = new Regex(@"^\d{1,4}$");
            string errorMessage = "Некорректный размер изображения";
            TextBox currentTextBox = sender as TextBox;

            if (!sizeReg.IsMatch(currentTextBox.Text))
            {
                this.errorProvider1.SetError(currentTextBox, errorMessage);
                this.isValid = false;
            }
            else
            {
                this.isValid = true;
                this.errorProvider1.SetError(currentTextBox, "");
                switch (currentTextBox.Name)
                {
                    case "tb_width":
                        this.ImageWidth = Int32.Parse(this.tb_width.Text);
                        break;
                    case "tb_heigth":
                        this.ImageHeight = Int32.Parse(this.tb_heigth.Text);
                        break;
                    default:
                        break;
                }
            }
        }
    private void WriteBson(BsonWriter writer, Regex regex)
    {
      // Regular expression - The first cstring is the regex pattern, the second
      // is the regex options string. Options are identified by characters, which 
      // must be stored in alphabetical order. Valid options are 'i' for case 
      // insensitive matching, 'm' for multiline matching, 'x' for verbose mode, 
      // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode 
      // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode.

      string options = null;

      if (HasFlag(regex.Options, RegexOptions.IgnoreCase))
        options += "i";

      if (HasFlag(regex.Options, RegexOptions.Multiline))
        options += "m";

      if (HasFlag(regex.Options, RegexOptions.Singleline))
        options += "s";

      options += "u";

      if (HasFlag(regex.Options, RegexOptions.ExplicitCapture))
        options += "x";

      writer.WriteRegex(regex.ToString(), options);
    }
Example #29
0
        private IList<string> ParseBaseTypes(string fileContents)
        {
            const string tagName = "baseType";
            string regexPattern = "class\\s+?" + _className + "(?<" + tagName + ">(.|\\s)*?)(\\{|where)";

            var regex = new Regex(regexPattern, RegexOptions.Multiline | RegexOptions.Compiled);

            var match = regex.Match(fileContents);

            if (!match.Success)
            {
                return new List<string>();
            }

            var contents = match.Groups[tagName].Value;
            var firstColonIndex = contents.IndexOf(':');

            if (firstColonIndex < 0)
            {
                return new List<string>();
            }

            contents = contents.Substring(firstColonIndex + 1, contents.Length - firstColonIndex - 1);
            contents = contents.Replace("\r", String.Empty);
            contents = contents.Replace("\n", String.Empty);
            contents = contents.Replace("\t", String.Empty);
            contents = contents.Replace(" ", String.Empty);
            var result = contents.Split(',').ToList();

            return result;
        }
Example #30
0
 public void ShouldRegexMatchTwoLines()
 {
   string content = string.Format("blah:{0}blah", Environment.NewLine);
   Regex regex = new Regex("^.*$", RegexOptions.Multiline);
   regex.IsMatch(content).Should().BeTrue();
   regex.Matches(content).Count.Should().Be(2);
 }