public void SplitRemoveEmptyEntries_Matches_Core_Split_With_Same_Option()
        {
            string input = "() Hello . World?";

            string[] delimiters = { "()", ".", "?" };
            string[] expected   = { " Hello ", " World" };

            var coreSplit = RegexUtility.Split(input, delimiters, splitOptions: SplitOptions.RemoveEmptyEntries);
            var result    = RegexUtility.SplitRemoveEmptyEntries(input, delimiters);

            result.ShouldBe(coreSplit);
            result.ShouldBe(expected);
        }
        public void SplitTrimWhitespace_Matches_Core_Split_With_Same_Option()
        {
            string input = "Hello . World";

            string[] delimiters = { "." };
            string[] expected   = { "Hello", "World" };

            var coreSplit = RegexUtility.Split(input, delimiters, splitOptions: SplitOptions.TrimWhitespace);
            var result    = RegexUtility.SplitTrimWhitespace(input, delimiters);

            result.ShouldBe(coreSplit);
            result.ShouldBe(expected);
        }
Ejemplo n.º 3
0
        public static void GetAlphaNumericRegex_Should_Return_Failed_Match()
        {
            // arrange
            var values = new List <string> {
                "aa%dfgh", "asd"
            };

            // act
            var result = RegexUtility.IsMatch(values, RegexUtility.GetAlphaNumericRegex(3, 6));

            // assert
            Assert.False(result);
        }
        public void SplitIncludeDelimiters_Matches_Core_Split_With_Same_Option()
        {
            string input = "123xx456yy789";

            string[] delimiters = { "xx", "yy" };
            string[] expected   = { "123", "xx", "456", "yy", "789" };

            var coreSplit = RegexUtility.Split(input, delimiters, splitOptions: SplitOptions.IncludeDelimiters);
            var result    = RegexUtility.SplitIncludeDelimiters(input, delimiters);

            result.ShouldBe(coreSplit);
            result.ShouldBe(expected);
        }
        public void SplitMatchWholeWords_Matches_Core_Split_With_Same_Option()
        {
            string input = "StackOverflow Stack OverStack";

            string[] delimiters = { "Stack" };
            string[] expected   = { "StackOverflow ", " OverStack" };

            var coreSplit = RegexUtility.Split(input, delimiters, splitOptions: SplitOptions.MatchWholeWords);
            var result    = RegexUtility.SplitMatchWholeWords(input, delimiters);

            result.ShouldBe(coreSplit);
            result.ShouldBe(expected);
        }
Ejemplo n.º 6
0
        public static void GetPasswordRegex_Should_Return_Failed_Match_By_Number_All_Criterias()
        {
            // arrange
            var values = new List <string> {
                "ABcd12$%", "R$aasdfgh"
            };

            // act
            var result = RegexUtility.IsMatch(values, RegexUtility.GetPasswordRegex(8, 16, true, true, true, true));

            // assert
            Assert.False(result);
        }
Ejemplo n.º 7
0
        public static void GetPasswordRegex_Should_Return_Success_Match_All_Criterias()
        {
            // arrange
            var values = new List <string> {
                "ABcd12$%", "asdfgh ssR1$"
            };

            // act
            var result = RegexUtility.IsMatch(values, RegexUtility.GetPasswordRegex(8, 16, true, true, true, true));

            // assert
            Assert.True(result);
        }
Ejemplo n.º 8
0
        public void MatchesToNamedGroupsLookup_Returns_Expected_Result()
        {
            var input   = "123-456-7890 hello 098-765-4321";
            var pattern = @"(?<AreaCode>\d{3})-(?<First>\d{3})-(?<Last>\d{4})";

            string[] groupNames = new[] { "AreaCode", "First", "Last" };

            ILookup <string, string> result = RegexUtility.MatchesToNamedGroupsLookup(input, pattern);

            result.Count.ShouldBe(groupNames.Length);
            result[groupNames[0]].Count().ShouldBe(2);
            result[groupNames[1]].ShouldContain("456");
            result[groupNames[2]].ShouldContain("4321");
        }
Ejemplo n.º 9
0
 public MembershipService(ILogger logger,
                          IUserFactory userFactory,
                          IUserService userService,
                          RegexUtility regexUtility,
                          IUserVerificationFactory userVerificationFactory,
                          IPasswordVerificationFactory passwordVerificationFactory,
                          IUnitOfWork unitOfWork)
 {
     _logger                      = logger;
     _userService                 = userService;
     _regexUtility                = regexUtility;
     _userVerificationFactory     = userVerificationFactory;
     _passwordVerificationFactory = passwordVerificationFactory;
     _unitOfWork                  = unitOfWork;
 }
Ejemplo n.º 10
0
        public void MatchesToNamedGroupsDictionaries_Returns_Expected_Result()
        {
            var input   = "123-456-7890 hello 098-765-4321";
            var pattern = @"(?<AreaCode>\d{3})-(?<First>\d{3})-(?<Last>\d{4})";

            string[] groupNames = new[] { "AreaCode", "First", "Last" };

            Dictionary <string, string>[] results = RegexUtility.MatchesToNamedGroupsDictionaries(input, pattern);

            results.Length.ShouldBe(2);
            results[0].Keys.Count.ShouldBe(groupNames.Length);
            results[1][groupNames[0]].ShouldBe("098");
            results[1][groupNames[1]].ShouldBe("765");
            results[1][groupNames[2]].ShouldBe("4321");
        }
Ejemplo n.º 11
0
        public Options(RegexOptions applyOptions, RegexOptions disableOptions)
        {
            if (!RegexUtility.IsValidInlineOptions(applyOptions))
            {
                throw new ArgumentException(ExceptionHelper.RegexOptionsNotConvertibleToInlineChars, nameof(applyOptions));
            }

            if (!RegexUtility.IsValidInlineOptions(disableOptions))
            {
                throw new ArgumentException(ExceptionHelper.RegexOptionsNotConvertibleToInlineChars, nameof(disableOptions));
            }

            _applyOptions   = applyOptions;
            _disableOptions = disableOptions;
        }
Ejemplo n.º 12
0
 /// <summary>
 /// 替换条件表达式中的条件
 /// </summary>
 /// <param name="expression"></param>
 /// <param name="condition"></param>
 /// <returns></returns>
 private string ReplaceParameterToValue(string expression, Dictionary <string, string> condition)
 {
     foreach (var item in condition)
     {
         if (!RegexUtility.IsNumeric(item.Value))
         {
             var str = "\"" + item.Value + "\"";
             expression = expression.Replace(item.Key, str);
         }
         else
         {
             expression = expression.Replace(item.Key, item.Value);
         }
     }
     return(expression);
 }
Ejemplo n.º 13
0
        internal override void AppendTo(StringBuilder builder)
        {
            if (string.IsNullOrEmpty(_text))
            {
                return;
            }

            for (int i = 0; i < _text.Length; i++)
            {
                if (_text[i] == '$')
                {
                    RegexUtility.EscapeSubstitution(_text, i, builder);
                    return;
                }
            }

            builder.Append(_text);
        }
        /// <summary>
        /// 判断变量格式是否正确,并赋值给`variable`。
        ///     `isExist`: 指定变量在使用之前,是否存在。
        /// </summary>
        /// <param name="varStr"></param>
        /// <param name="isExist"></param>
        /// <param name="variable"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        protected bool IsMatchVar(string varStr, bool isExist, ref string variable, out string error)
        {
            if (!RegexUtility.IsMatchVariable(varStr))
            {
                error = GetMatchVariableErrorString(varStr);
                return(false);
            }

            if (ScenarioBlackboard.Contains(varStr) != isExist)
            {
                error = GetVariableExistErrorString(varStr, !isExist);
                return(false);
            }

            variable = varStr;
            error    = null;
            return(true);
        }
Ejemplo n.º 15
0
        public void IPRangeTest()
        {
            new Regex($"^{RegexUtility.IPRange("192.168.1~2.23~34")}$").Then(_ =>
            {
                AssertIPRangeTrue(_, new[] { "192.168.1.23", "192.168.1.29", "192.168.1.30", "192.168.1.34" });
                AssertIPRangeFalse(_, new[] { "192.168.1.22", "192.168.1.35", "192.168.3.30", "192.168.3.34" });
            });

            new Regex($"^{RegexUtility.IPRange("192.*.1~2.23~34")}$").Then(_ =>
            {
                AssertIPRangeTrue(_, new[] { "192.1.1.23", "192.100.1.29", "192.200.1.30", "192.255.1.34" });
                AssertIPRangeFalse(_, new[] { "192.168.1.22", "192.168.1.35", "192.168.3.30", "192.168.3.34" });
            });

            Assert.Throws <FormatException>(() => RegexUtility.IPRange("192.168.1~2"));
            Assert.Throws <FormatException>(() => RegexUtility.IPRange("192.168.256.1"));
            Assert.Throws <FormatException>(() => RegexUtility.IPRange("192.168.1~2.23~256"));
        }
Ejemplo n.º 16
0
 private static StringBuilder GetImageName(string[] fileName, ref StringBuilder sb)
 {
     if (fileName != null && fileName.Length > 0)
     {
         for (int j = 0; j < fileName.Length; j++)
         {
             if (GEditorTexturePackerImporter.IsTextureFile(fileName[j]))
             {
                 if (!RegexUtility.IsHasCHZN(Path.GetFileName(fileName[j])))
                 {
                     sb.Append(fileName[j]);
                     sb.Append(" ");
                 }
             }
         }
     }
     return(sb);
 }
Ejemplo n.º 17
0
        public override bool ParseArgs(IScenarioContent content, ref VarArgs args, out string error)
        {
            // var a;
            // var b = 10;
            // var c = b;
            if (content.length != 2 && content.length != 4)
            {
                error = GetLengthErrorString(2, 4);
                return(false);
            }

            // 变量名只能包含数字,字母(中文),下划线,且不能以数字开头
            if (!RegexUtility.IsMatchVariable(content[1]))
            {
                error = GetMatchVariableErrorString(content[1]);
                return(false);
            }
            args.name = content[1];

            //// 你也可以使用这个方法,这里确保了变量必须不存在
            //if (!IsMatchVar(content[1], false, ref args.name, out error))
            //{
            //    return false;
            //}

            args.value = 0;

            if (content.length == 4)
            {
                if (content[2] != "=")
                {
                    error = GetMatchOperatorErrorString(content[2], "=");
                    return(false);
                }

                if (!ParseOrGetVarValue(content[3], ref args.value, out error))
                {
                    return(false);
                }
            }

            error = null;
            return(true);
        }
Ejemplo n.º 18
0
        public static int GetBoardPageCount(string sourceHtml)
        {
            return(GetBoardPageCountPro(sourceHtml));

            #region  用的匹配方式
            string regexstring = RegexStringLib.GetBoardPageCount();
            string result      = RegexUtility.GetMatch(sourceHtml, regexstring);

            int pageCount;
            if (int.TryParse(result, out pageCount))
            {
                return(pageCount);
            }
            else
            {
                return(-1);
            }
            #endregion
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EditableComboViewModel"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="commonServices">The common services.</param>
        /// <param name="loggerFactory">The logger factory.</param>
        public EditableComboViewModel(
            IContext context,
            IBaseCommonServices commonServices,
            ILogger <EditableComboViewModel> loggerFactory)
            : base(context, commonServices, loggerFactory)
        {
            MaskExpression  = "9999aa";
            RegexExpression = "0000>LL"; //1111Ab 0000Xx

            this.Validator = new Action <IObservableClass>(_ =>
            {
                var regex = RegexUtility.MaskToRegexConverter(RegexExpression);

                if (string.IsNullOrEmpty(RegexSample) || !regex.IsMatch(RegexSample))
                {
                    Properties[nameof(RegexSample)].Errors.Add("TextSample is fout.");
                }
            });
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Match2s the item.
        /// </summary>
        /// <param name="m">M.</param>
        /// <param name="Item">Item.</param>
        /// <param name="BaseUrl">Base URL.</param>
        /// <param name="ItemUrlCaseSensitive">If set to <c>true</c> item URL case sensitive.</param>
        public static void Match2Item(Match m, ref Article Item, string BaseUrl, bool ItemUrlCaseSensitive = false)
        {
            //url
            Item.Url = new Uri(new Uri(BaseUrl), RegexUtility.TryGetString(m, "Url", Item.Url, false)).AbsoluteUri;

            //title
            Item.Title = RegexUtility.TryGetString(m, "Title", Item.Title);
            //降低Clean级别
            if (string.IsNullOrEmpty(Item.Title))
            {
                Item.Title = HTMLCleaner.CleanHTML(Item.Title, true);
            }

            //text
            Item.HtmlContent = RegexUtility.TryGetString(m, "Text", Item.HtmlContent, false);

            //Author Info
            Item.Author = RegexUtility.TryGetString(m, "AuthorName", Item.Author);
            Item.Source = RegexUtility.TryGetString(m, "Source", Item.Source);

            if (!String.IsNullOrWhiteSpace(Item.Source))
            {
                Item.Source = TextCleaner.FullClean(Item.Source);
            }

            //Media Info
            Item.MediaName = RegexUtility.TryGetString(m, "MediaName", Item.MediaName);
            //time


            if (m.Groups["PubDate"].Success)
            {
                Item.PubDate = DateTimeParser.Parser(HTMLCleaner.CleanHTML(m.Groups["PubDate"].Value, true));
            }

            if (Item.PubDate <= DateTime.MinValue)
            {
                Item.PubDate = DateTime.Now;
            }

            Match2ItemCount(m, Item.ViewDataList);
        }
        /// <summary>
        /// 如果是数字,直接赋值;如果是变量,就获取变量
        /// </summary>
        /// <param name="numOrVar"></param>
        /// <param name="value"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        protected bool ParseOrGetVarValue(string numOrVar, ref int value, out string error)
        {
            if (!int.TryParse(numOrVar, out value))
            {
                if (!RegexUtility.IsMatchVariable(numOrVar))
                {
                    error = GetMatchVariableErrorString(numOrVar);
                    return(false);
                }

                if (!ScenarioBlackboard.TryGet(numOrVar, out value))
                {
                    error = GetVariableExistErrorString(numOrVar, false);
                    return(false);
                }
            }

            error = null;
            return(true);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// called by Match2Item only
        /// </summary>
        /// <param name="m"></param>
        /// <param name="PreItemCount"></param>
        public static void Match2ItemCount(Match m, List <ViewData> PreItemCount = null)
        {
            if (!m.Groups["View"].Success && !m.Groups["Reply"].Success && !m.Groups["Forward"].Success)
            {
                return;
            }

            ViewData ItemCount = new ViewData();

            ItemCount.FetchTime = DateTime.Now;
            ItemCount.View      = RegexUtility.TryGetInt(m, "View", 0);
            ItemCount.Reply     = RegexUtility.TryGetInt(m, "Reply", 0);
            ItemCount.Forward   = RegexUtility.TryGetInt(m, "Forward", 0);

            if (PreItemCount == null)
            {
                PreItemCount = new List <ViewData>();
            }

            PreItemCount.Add((ItemCount));
        }
Ejemplo n.º 23
0
        public OperationExpressionCalculator(IEnumerable <IOperationRule> rules)
        {
            if (rules == null || !rules.Any())
            {
                throw new ArgumentException("rules is null ro empty", "rules");
            }

            StringBuilder pattern = new StringBuilder(string.Format("(?:{0}[^{0}]*{0})", STRING_DELIMITER));

            foreach (string item in rules.Select((item) => item.OperandPattern).Where((item) => item != null).OrderByDescending((item) => item.Length).Distinct(StringComparer.OrdinalIgnoreCase))
            {
                pattern.AppendFormat("|(?:{0})", item);
            }
            foreach (string item in rules.Select((item) => item.OperatorSymbol).OrderByDescending((item) => item.Length).Distinct(StringComparer.OrdinalIgnoreCase))
            {
                pattern.AppendFormat("|(?:{0})", RegexUtility.Encode(item));
            }

            this.m_whitespaceRegex = new Regex("\\s+", RegexOptions.Compiled);
            this.m_expressionRegex = new Regex(pattern.ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
            this.m_wellFormedRegex = new Regex(pattern.AppendFormat("|\\{0}|\\{1}", LEFT_BRACKET, RIGHT_BRACKET).ToString(), RegexOptions.Compiled | RegexOptions.IgnoreCase);
            this.m_bracketRegex    = new Regex(string.Format(
                                                   "(?>" +
                                                   "^{2}*" +
                                                   "(?:" +
                                                   "(?:(?'left'{0}){2}+)+" +
                                                   "(?:(?'inner-left'{1}){2}*)+" +
                                                   ")*" +
                                                   "(?(left)(?!))$" +
                                                   ")",
                                                   "\\" + LEFT_BRACKET,
                                                   "\\" + RIGHT_BRACKET,
                                                   string.Format("[^\\{0}\\{1}]", LEFT_BRACKET, RIGHT_BRACKET)), RegexOptions.Compiled);

            this.m_rules = rules.ToIDictionary((item) => item.OperatorSymbol);
        }
Ejemplo n.º 24
0
        public void SendMail(Applicant applicant, string body)
        {
            if (string.IsNullOrEmpty(applicant.EMail) || !RegexUtility.IsValidEmail(applicant.EMail))
            {
                return;
            }

            var mailMessage = new MailMessage();

            mailMessage.To.Add(applicant.EMail);
            mailMessage.From       = new MailAddress("*****@*****.**");
            mailMessage.Body       = body;
            mailMessage.Subject    = "Confirmation Mail";
            mailMessage.IsBodyHtml = true;
            if (applicant.CV.IsNotNull() && applicant.CV.Contents.IsNotNull())
            {
                mailMessage.Attachments.Add(
                    new Attachment(new MemoryStream(applicant.CV.Contents), applicant.CV.ContentType)
                {
                    Name = applicant.CV.FileName
                });
            }
            this.emailService.Send(mailMessage);
        }
Ejemplo n.º 25
0
        internal NamedGroupSubstitution(string groupName)
        {
            RegexUtility.CheckGroupName(groupName);

            GroupName = groupName;
        }
Ejemplo n.º 26
0
 public void MaskToRegexDoNotMatchTest(string mask, string value) =>
 Assert.IsFalse(RegexUtility.MaskToRegexConverter(mask).IsMatch(value));
Ejemplo n.º 27
0
 public void MaskToRegExTest(string mask, string result) =>
 Assert.AreEqual(RegexUtility.MaskToRegexStringConverter(mask), result);
Ejemplo n.º 28
0
        void httper_RequestStringCompleted(object sender, RequestStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                if (e.ResponseString != string.Empty)
                {
                    if (e.UserState.ToString() == "GETLIST")
                    {
                        #region 获取列表
                        #region 正则
                        MatchCollection mc = RegexUtility.GetMatchFull(e.ResponseString, tbxPreListRegex.Text.Trim(), RegexOptions.Singleline | RegexOptions.IgnoreCase);
                        if (mc != null)
                        {
                            foreach (Match m in mc)
                            {
                                WebContentListInfo wcli = new WebContentListInfo();
                                wcli.Title       = m.Groups[1].Value.Trim();
                                wcli.ContentList = new List <WebContentInfo>();

                                MatchCollection mcContent = RegexUtility.GetMatchFull(m.Groups[2].Value, tbxListRegex.Text.Trim());
                                if (mcContent != null)
                                {
                                    foreach (Match mContent in mcContent)
                                    {
                                        WebContentInfo wci = new WebContentInfo();
                                        wci.Title = mContent.Groups[2].Value.Trim();
                                        wci.Url   = mContent.Groups[1].Value.Trim();

                                        wcli.ContentList.Add(wci);
                                    }

                                    WebContentLists.Add(wcli);
                                }
                            }
                        }
                        #endregion
                        #region 显示
                        this.lvList.Items.Clear();
                        foreach (WebContentInfo info in WebContentLists[0].ContentList)
                        {
                            ListViewItem lv = new ListViewItem(info.Title);

                            ListViewItem.ListViewSubItem lvsi  = new ListViewItem.ListViewSubItem(lv, info.Url);
                            ListViewItem.ListViewSubItem lvsi2 = new ListViewItem.ListViewSubItem(lv, info.Title);

                            lv.SubItems.Add(lvsi);
                            lv.SubItems.Add(lvsi2);

                            this.lvList.Items.Add(lv);
                        }
                        MessageBox.Show(this, string.Format("{0}章完成!", WebContentLists.Count));
                        this.btnGetList.Enabled = true;
                        #endregion }
                        #endregion
                    }
                    else
                    {
                        #region 获取内容
                        WebContentInfo wci = (WebContentInfo)e.UserState;

                        string content = RegexUtility.ReplaceRegex(
                            tbxPreContentRegex.Text.Trim(),
                            e.ResponseString,
                            "",
                            RegexOptions.Singleline | RegexOptions.IgnoreCase
                            );
                        MatchCollection mc = RegexUtility.GetMatchFull(
                            content,
                            tbxContentRegex.Text.Trim(),
                            RegexOptions.Singleline | RegexOptions.IgnoreCase
                            );
                        if (mc != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.Append(wci.Title + Environment.NewLine);
                            foreach (Match m in mc)
                            {
                                if (m.Groups[1].Value.IndexOf("盗墓笔记网友留言") < 0)
                                {
                                    sb.Append(m.Groups[1].Value + Environment.NewLine);
                                }
                            }
                            sb.Append(Environment.NewLine);
                            sb.Append(Environment.NewLine);


                            string savepath = Path.Combine(
                                AppDomain.CurrentDomain.BaseDirectory,
                                "down"
                                );
                            if (!Directory.Exists(savepath))
                            {
                                Directory.CreateDirectory(savepath);
                            }

                            try
                            {
                                FileStream fs = new FileStream(
                                    Path.Combine(savepath, this.WebContentLists[0].Title + ".txt"),
                                    FileMode.Append
                                    );
                                StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(true, true));
                                sw.Write(Natsuhime.Web.Utils.RemoveHtml(sb.ToString()));
                                sw.Flush();
                                sw.Close();
                                fs.Close();


                                this.WebContentLists[0].ContentList.Remove(wci);
                                DownNextContent();
                            }
                            catch (Exception ex)
                            {
                                this.btnGetContent.Enabled = true;
                            }
                        }
                        #endregion
                    }
                }
                else
                {
                    MessageBox.Show("返回空");
                }
            }
            else
            {
                MessageBox.Show(e.Error.Message);
            }
        }
Ejemplo n.º 29
0
        public void Can_Format_CamelCase_And_Capitalize_First_Character(string input, string expected)
        {
            string result = RegexUtility.FormatCamelCase(input, camelCaseOptions: CamelCaseOptions.CapitalizeFirstCharacter);

            result.ShouldBe(expected);
        }
Ejemplo n.º 30
0
        public void Can_Format_CamelCase_Inputs_With_Numbers(string input, string expected)
        {
            string result = RegexUtility.FormatCamelCase(input);

            result.ShouldBe(expected);
        }