Exemplo n.º 1
0
        public void NullThis()
        {
            var e = Assert.Throws <ArgumentNullException>(() =>
                                                          RegexExtensions.ToOption <Group>(null));

            Assert.That(e.ParamName, Is.EqualTo("group"));
        }
        public Dictionary <string, int> GetWordOccurences(string text, List <Stopwords> stopwords)
        {
            Dictionary <string, int> occurenceDictionary = new Dictionary <string, int>();
            var wordList = RegexExtensions.listMatchingRegex(RegexExtensions.isWord, text);

            foreach (var word in wordList)
            {
                var searchWord = word.ToLower().Trim();

                if (!stopwords
                    .Select(x => x.Stopword)
                    .Contains(searchWord))
                {
                    if (!occurenceDictionary.ContainsKey(searchWord))
                    {
                        occurenceDictionary.Add(searchWord, 1);
                    }
                    else
                    {
                        occurenceDictionary[searchWord] += 1;
                    }
                }
            }

            return(occurenceDictionary);
        }
Exemplo n.º 3
0
        public void ParseConcat()
        {
            var rex    = 'a'.Literal() * 'b'.Literal();
            var parsed = RegexExtensions.Parse("ab");

            Assert.Equal(rex, parsed);
        }
Exemplo n.º 4
0
        public void ParseNested()
        {
            var rex    = 'a'.Literal() * ('b'.Literal() * 'c'.Literal()).Star();
            var parsed = RegexExtensions.Parse("a(bc)*");

            Assert.Equal(rex, parsed);
        }
Exemplo n.º 5
0
        public void ParsePlus()
        {
            var rex    = 'a'.Literal().Plus();
            var parsed = RegexExtensions.Parse("a+");

            Assert.Equal(rex, parsed);
        }
Exemplo n.º 6
0
        public void ParseQuestion()
        {
            var rex    = 'a'.Literal().Question();
            var parsed = RegexExtensions.Parse("a?");

            Assert.Equal(rex, parsed);
        }
Exemplo n.º 7
0
        public void ParseStar()
        {
            var rex    = 'a'.Literal().Star();
            var parsed = RegexExtensions.Parse("a*");

            Assert.Equal(rex, parsed);
        }
 /// <summary>
 ///     NOTE: Code-generation-invoked method, method name and parameter order matters
 /// </summary>
 /// <param name="text">regex pattern</param>
 /// <returns>pattern</returns>
 public static Regex ExprRegexNodeCompilePattern(string text)
 {
     try {
         return RegexExtensions.Compile(text, out string patternText);
     }
     catch (ArgumentException ex) {
         throw new EPException("Failed to compile regex pattern '" + text + "': " + ex.Message, ex);
     }
 }
Exemplo n.º 9
0
 private static void CheckTryMatch(string input, string pattern, bool expectedSuccess, params string[] expectedGroups)
 {
     Assert.IsTrue(expectedSuccess == RegexExtensions.TryMatch(input, pattern, out var result));
     for (int i = 0; expectedSuccess && i < expectedGroups?.Length; i++)
     {
         Assert.IsTrue(result.Groups.Count > i + 1);
         Assert.AreEqual(expectedGroups[i], result.Groups[i + 1].Value);
     }
 }
        public static void AssertContentMatches(this Stream s, string content)
        {
            var s2 = new MemoryStream((int)s.Length);

            AsyncPump.Run(() => s.CopyToAsync(s2));
            s2.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(s2))
            {
                var actualContent = reader.ReadToEnd();
                var regex         = new Regex($"^{RegexExtensions.GlobToRexex(content)}$", RegexOptions.IgnoreCase);
                Assert.True(regex.IsMatch(actualContent),
                            string.Format("\r\n{0} and \r\n{1} do not match.", actualContent, content));
            }
        }
Exemplo n.º 11
0
        public override ExprNode Validate(ExprValidationContext validationContext)
        {
            if (ChildNodes.Length != 2) {
                throw new ExprValidationException("The regexp operator requires 2 child expressions");
            }

            // check pattern child node
            var patternChildType = ChildNodes[1].Forge.EvaluationType;
            if (patternChildType != typeof(string)) {
                throw new ExprValidationException("The regexp operator requires a String-type pattern expression");
            }

            var constantPattern = ChildNodes[1].Forge.ForgeConstantType.IsCompileTimeConstant;

            // check eval child node - can be String or numeric
            var evalChildType = ChildNodes[0].Forge.EvaluationType;
            var isNumericValue = TypeHelper.IsNumeric(evalChildType);
            if ((evalChildType != typeof(string)) && (!isNumericValue)) {
                throw new ExprValidationException(
                    "The regexp operator requires a String or numeric type left-hand expression");
            }

            if (constantPattern) {
                var patternText = (string) ChildNodes[1].Forge.ExprEvaluator.Evaluate(null, true, null);

                Regex pattern;
                try {
                    pattern = RegexExtensions.Compile(patternText, out patternText);
                }
                catch (ArgumentException ex) {
                    throw new ExprValidationException(
                        "Failed to compile regex pattern '" + patternText + "': " + ex.Message,
                        ex);
                }

                var patternInit = NewInstance<Regex>(Constant(patternText));
                _forge = new ExprRegexpNodeForgeConst(this, isNumericValue, pattern, patternInit);
            }
            else {
                _forge = new ExprRegexpNodeForgeNonconst(this, isNumericValue);
            }

            return null;
        }
        public async Task <ScrapedData> ScrapeData(string text)
        {
            var scrapedData = new ScrapedData();

            if (!string.IsNullOrEmpty(text))
            {
                scrapedData.BodyContent = text;


                var links = RegexExtensions.listMatchingRegex(RegexExtensions.isLink, text);

                foreach (var link in links)
                {
                    scrapedData.Links.Add(link);
                }
            }


            return(scrapedData);
        }
Exemplo n.º 13
0
        /// <summary>
        /// 1ログ1スペルに対して判定する
        /// </summary>
        /// <param name="spell">スペル</param>
        /// <param name="logLine">ログ</param>
        public void MatchCore(
            Models.Spell spell,
            string logLine)
        {
            var regex        = spell.Regex;
            var notifyNeeded = false;

            if (!spell.IsInstance)
            {
                // マッチング計測開始
                spell.StartMatching();

                // 開始条件を確認する
                if (ConditionUtility.CheckConditionsForSpell(spell))
                {
                    // 正規表現が無効?
                    if (!spell.RegexEnabled ||
                        regex == null)
                    {
                        var keyword = spell.KeywordReplaced;
                        if (string.IsNullOrWhiteSpace(keyword))
                        {
                            return;
                        }

                        // キーワードが含まれるか?
                        if (logLine.Contains(keyword, StringComparison.OrdinalIgnoreCase))
                        {
                            var targetSpell = spell;

                            // ヒットしたログを格納する
                            targetSpell.MatchedLog = logLine;

                            // スペル名(表示テキスト)を置換する
                            var replacedTitle = ConditionUtility.GetReplacedTitle(targetSpell);

                            // PC名を置換する
                            replacedTitle = XIVPluginHelper.Instance.ReplacePartyMemberName(
                                replacedTitle,
                                Settings.Default.PCNameInitialOnDisplayStyle);

                            targetSpell.SpellTitleReplaced = replacedTitle;
                            targetSpell.UpdateDone         = false;
                            targetSpell.OverDone           = false;
                            targetSpell.BeforeDone         = false;
                            targetSpell.TimeupDone         = false;

                            var now = DateTime.Now;

                            // ホットバーからリキャスト時間の読込みを試みる
                            if (!this.TryGetHotbarRecast(targetSpell, out double d))
                            {
                                d = targetSpell.RecastTime;
                            }

                            targetSpell.CompleteScheduledTime = now.AddSeconds(d);
                            targetSpell.MatchDateTime         = now;

                            // マッチング計測終了
                            spell.EndMatching();

                            // マッチ時点のサウンドを再生する
                            targetSpell.Play(targetSpell.MatchSound, targetSpell.MatchAdvancedConfig);
                            targetSpell.Play(targetSpell.MatchTextToSpeak, targetSpell.MatchAdvancedConfig);

                            notifyNeeded = true;

                            // 遅延サウンドタイマを開始する
                            targetSpell.StartOverSoundTimer();
                            targetSpell.StartBeforeSoundTimer();
                            targetSpell.StartTimeupSoundTimer();
                        }
                    }
                    else
                    {
                        // 正規表現でマッチングする
                        var match = regex.Match(logLine);
                        if (match.Success)
                        {
#if DEBUG
                            if (logLine.Contains("MARK"))
                            {
                                Debug.WriteLine("MARK");
                            }
#endif
                            var targetSpell = default(Spell);

                            void setTitle()
                            {
                                targetSpell = spell;

                                // ヒットしたログを格納する
                                targetSpell.MatchedLog = logLine;

                                // スペル名(表示テキスト)を置換する
                                var replacedTitle = match.Result(ConditionUtility.GetReplacedTitle(targetSpell));

                                // PC名を置換する
                                replacedTitle = XIVPluginHelper.Instance.ReplacePartyMemberName(
                                    replacedTitle,
                                    Settings.Default.PCNameInitialOnDisplayStyle);

                                // インスタンス化する?
                                if (targetSpell.ToInstance)
                                {
                                    // 同じタイトルのインスタンススペルを探す
                                    // 存在すればそれを使用して、なければ新しいインスタンスを生成する
                                    targetSpell = SpellTable.Instance.GetOrAddInstance(
                                        replacedTitle,
                                        targetSpell);
                                }
                                else
                                {
                                    targetSpell.SpellTitleReplaced = replacedTitle;
                                }
                            }

                            // スペルタイトルを編集する
                            setTitle();

                            targetSpell.UpdateDone = false;
                            targetSpell.OverDone   = false;
                            targetSpell.BeforeDone = false;
                            targetSpell.TimeupDone = false;

                            var now = DateTime.Now;

                            // 効果時間を決定する
                            // グループ "duration" をキャプチャーしていた場合は効果時間を置換する
                            // 最大値9999を超えていた場合は無視する
                            var duration = targetSpell.RecastTime;

                            if (RegexExtensions.TryGetDuration(match, out double d))
                            {
                                duration = d;
                            }
                            else
                            {
                                // ホットバーからリキャスト時間の読込みを試みる
                                if (this.TryGetHotbarRecast(targetSpell, out double durationFromHotbar))
                                {
                                    duration = durationFromHotbar;
                                }
                            }

                            targetSpell.CompleteScheduledTime = now.AddSeconds(duration);

                            // スペル対象を保存する
                            // グループ "target" をキャプチャーしていた場合はその文字列を保存する
                            var targetName = match.Groups["target"].Value;
                            if (!string.IsNullOrWhiteSpace(targetName))
                            {
                                targetSpell.TargetName = targetName;
                            }

                            // マッチ日時を格納する
                            targetSpell.MatchDateTime = now;

                            // マッチング計測終了
                            spell.EndMatching();

                            // マッチ時点のサウンドを再生する
                            targetSpell.Play(targetSpell.MatchSound, targetSpell.MatchAdvancedConfig);

                            if (!string.IsNullOrWhiteSpace(targetSpell.MatchTextToSpeak))
                            {
                                var tts = match.Result(targetSpell.MatchTextToSpeak);
                                targetSpell.Play(tts, targetSpell.MatchAdvancedConfig);
                            }

                            notifyNeeded = true;

                            // 遅延サウンドタイマを開始する
                            targetSpell.StartOverSoundTimer();
                            targetSpell.StartBeforeSoundTimer();
                            targetSpell.StartTimeupSoundTimer();
                        }
                    }
                }
            }

            // 延長をマッチングする
            if (spell.MatchDateTime > DateTime.MinValue)
            {
                var keywords      = new string[] { spell.KeywordForExtendReplaced1, spell.KeywordForExtendReplaced2, spell.KeywordForExtendReplaced3 };
                var regexes       = new Regex[] { spell.RegexForExtend1, spell.RegexForExtend2, spell.RegexForExtend3 };
                var timeToExtends = new double[] { spell.RecastTimeExtending1, spell.RecastTimeExtending2, spell.RecastTimeExtending3 };

                for (int i = 0; i < keywords.Length; i++)
                {
                    var keywordToExtend = keywords[i];
                    var regexToExtend   = regexes[i];
                    var timeToExtend    = timeToExtends[i];

                    // マッチングする
                    var exntended = false;

                    if (!spell.RegexEnabled ||
                        regexToExtend == null)
                    {
                        if (!string.IsNullOrWhiteSpace(keywordToExtend))
                        {
                            exntended = logLine.Contains(keywordToExtend, StringComparison.OrdinalIgnoreCase);
                        }
                    }
                    else
                    {
                        var match = regexToExtend.Match(logLine);
                        exntended = match.Success;

                        if (exntended)
                        {
                            // targetをキャプチャーしている?
                            if (!string.IsNullOrWhiteSpace(spell.TargetName))
                            {
                                var targetName = match.Groups["target"].Value;
                                if (!string.IsNullOrWhiteSpace(targetName))
                                {
                                    // targetが当初のマッチングと一致するか確認する
                                    if (spell.TargetName != targetName)
                                    {
                                        exntended = false;
                                    }
                                }
                            }
                        }
                    }

                    if (!exntended)
                    {
                        continue;
                    }

                    var now = DateTime.Now;

                    // リキャストタイムを延長する
                    var newSchedule = spell.CompleteScheduledTime.AddSeconds(timeToExtend);
                    spell.BeforeDone = false;
                    spell.UpdateDone = false;

                    if (spell.ExtendBeyondOriginalRecastTime)
                    {
                        if (spell.UpperLimitOfExtension > 0)
                        {
                            var newDuration = (newSchedule - now).TotalSeconds;
                            if (newDuration > (double)spell.UpperLimitOfExtension)
                            {
                                newSchedule = newSchedule.AddSeconds(
                                    (newDuration - (double)spell.UpperLimitOfExtension) * -1);
                            }
                        }
                    }
                    else
                    {
                        var newDuration = (newSchedule - now).TotalSeconds;
                        if (newDuration > (double)spell.RecastTime)
                        {
                            newSchedule = newSchedule.AddSeconds(
                                (newDuration - (double)spell.RecastTime) * -1);
                        }
                    }

                    spell.CompleteScheduledTime = newSchedule;

                    if (!spell.IsNotResetBarOnExtended)
                    {
                        spell.MatchDateTime = now;
                    }

                    notifyNeeded = true;

                    // 遅延サウンドタイマを開始(更新)する
                    spell.StartOverSoundTimer();
                    spell.StartBeforeSoundTimer();
                    spell.StartTimeupSoundTimer();
                }
            }
            // end if 延長マッチング

            // ACT標準のSpellTimerに変更を通知する
            if (notifyNeeded)
            {
                this.UpdateNormalSpellTimer(spell, false);
                this.NotifyNormalSpellTimer(spell);
            }
        }
Exemplo n.º 14
0
 public static bool IsValidCep(this string cep)
 {
     return(cep != null && RegexExtensions.IsValidCep(cep));
 }
Exemplo n.º 15
0
 public static bool IsValidEmail(this string email)
 {
     return(email != null && RegexExtensions.IsValidEmail(email));
 }
Exemplo n.º 16
0
 public static Regex MatchGlob(string glob)
 {
     return(new Regex($"^{RegexExtensions.GlobToRexex(glob)}$", RegexOptions.IgnoreCase));
 }