繁体   English   中英

如果字符串在C#中包含2个句点

[英]If string contains 2 period in c#

我试图建立一个Reg表达式,如果文本框字符串在任何地方包含两个句点,它将执行我的代码。 到目前为止,这是我得到的:

Regex word = new Regex("(\\.){2,}");

if (word.IsMatch(textBoxSearch.Text))
{
    //my code here to execute
}

但是,它仅在两个句点在一起而不在字符串中的任何位置时执行...

这里不需要正则表达式,只需使用LINQ!

myString.Count(x => x == '.') == 2

2个或更多

myString.Where(x => x == '.').Skip(1).Any()

如果性能至关重要,则应使用循环。 这是三种方法(LINQ,循环,正则表达式)的比较:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Experiment
{
    public static class Program
    {
        static bool hasTwoPeriodsLinq(string text)
        {
            return text.Count(x => x == '.') == 2;
        }

        static bool hasTwoPeriodsLoop(string text)
        {
            int count = 0;

            for (int i = 0; i < text.Length; i++)
            {
                if (text[i] == '.')
                {
                    // This early break makes the loop faster than regex
                    if (count == 2)
                    {
                        return false;
                    }

                    count++;
                }
            }

            return count == 2;
        }

        static Regex twoPeriodsRegex = new Regex(@"^.*\..*\..*$", RegexOptions.Compiled);

        static bool hasTwoPeriodsRegex(string text)
        {
            return twoPeriodsRegex.IsMatch(text);
        }

        public static void Main(string[] args)
        {
            var text = @"The young Princess Bolk6nskaya had 
brought some work in a gold-embroidered vel- 
vet bag. Her pretty little upper lip, on which 
a delicate dark down was just perceptible, was 
too short for her teeth, but it lifted all the more 
sweetly, and was especially charming when she 
occasionally drew it down to meet the lower 
lip. As is always the case with a thoroughly at- 
tractive woman, her defectthe shortness of 
her upperlip and her half-open mouth seemed 
to be her own special and peculiar form of 
beauty. Everyone brightened at the sight of 
this pretty young woman, so soon to become 
a mother, so full of life and health, and carry- 
ing her burden so lightly. Old men and dull 
dispirited young ones who looked at her, after 
being in her company and talking to her a 
litttle while, felt as if they too were becoming, 
like her, full of life and health. All who talked 
to her, and at each word saw her bright smile 
and the constant gleam of her white teeth, 
thought that they were in a specially amiable 
mood that day. ";

            const int iterations = 100000;

            // Warm up... 
            for (int i = 0; i < iterations; i++)
            {
                hasTwoPeriodsLinq(text);
                hasTwoPeriodsLoop(text);
                hasTwoPeriodsRegex(text);
            }

            var watch = System.Diagnostics.Stopwatch.StartNew();

            // hasTwoPeriodsLinq
            watch.Restart();

            for (int i = 0; i < iterations; i++)
            {
                hasTwoPeriodsLinq(text);
            }

            watch.Stop();

            Console.WriteLine("hasTwoPeriodsLinq " + watch.ElapsedMilliseconds);

            // hasTwoPeriodsLoop
            watch.Restart();

            for (int i = 0; i < iterations; i++)
            {
                hasTwoPeriodsLoop(text);
            }

            watch.Stop();

            Console.WriteLine("hasTwoPeriodsLoop " + watch.ElapsedMilliseconds);

            // hasTwoPeriodsRegex
            watch.Restart();

            for (int i = 0; i < iterations; i++)
            {
                hasTwoPeriodsRegex(text);
            }

            watch.Stop();

            Console.WriteLine("hasTwoPeriodsRegex " + watch.ElapsedMilliseconds);
        }
    }
}

在这里尝试。

结果:

hasTwoPeriodsLinq 1280

hasTwoPeriodsLoop 54

hasTwoPeriodsRegex 74

您应该声明两个句点以及它们之间和之间的除句点以外的所有内容:

[^\.]*\.[^\.]*\.[^\.]*

尝试这个:

int count = source.Count(f => f == '.');

如果count == 2,那么一切都很好。

这根据我的测试工作:

^.*\..*\..*$

任何字符零次或多次,后跟一个句点,然后是零次或多次字符,后跟一个句点,然后再零次或多次出现任何字符。

当然,正如其他人指出的那样,此处使用Regex并不是最有效或最易读的方式。 正则表达式有一个学习曲线,如果有更简单的选择,将来的程序员可能不会喜欢这种不那么简单的方法。

如果要使用正则表达式,则可以使用Regex.Matches来检查计数。

if(Regex.Matches(stringinput, @"\.").Count == 2 )
{
//perform your operation
}

有几个人给出的例子来测试正好 2但这里有一个例子来测试至少 2个周期。 实际上,如果您愿意,也可以轻松修改此值以测试2个准确值。

 (.*\..*){2}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM