简体   繁体   English

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

[英]If string contains 2 period in c#

I'm trying to build a Reg Expression where if the textbox string contains two periods anywhere it will execute my code. 我试图建立一个Reg表达式,如果文本框字符串在任何地方包含两个句点,它将执行我的代码。 This is what I've got so far: 到目前为止,这是我得到的:

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

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

However, it only executes when there are two periods together and not anywhere within the string... 但是,它仅在两个句点在一起而不在字符串中的任何位置时执行...

There is no need for regex here, just use LINQ! 这里不需要正则表达式,只需使用LINQ!

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

Or for 2 or more : 2个或更多

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

If performance is crucial, you should use a loop. 如果性能至关重要,则应使用循环。 Here is a comparison of the three approaches (LINQ, loop, regex): 这是三种方法(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);
        }
    }
}

Try it here . 在这里尝试。

And the results: 结果:

hasTwoPeriodsLinq 1280 hasTwoPeriodsLinq 1280

hasTwoPeriodsLoop 54 hasTwoPeriodsLoop 54

hasTwoPeriodsRegex 74 hasTwoPeriodsRegex 74

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

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

Try this: 尝试这个:

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

If count == 2, you're all good. 如果count == 2,那么一切都很好。

This works according to my tests: 这根据我的测试工作:

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

Any character zero or more times followed by a period followed by any character zero or more times followed by a period followed by any character zero or more times. 任何字符零次或多次,后跟一个句点,然后是零次或多次字符,后跟一个句点,然后再零次或多次出现任何字符。

Of course, as others have pointed out, using Regex here is not the most efficient or readable way of doing it. 当然,正如其他人指出的那样,此处使用Regex并不是最有效或最易读的方式。 Regex has a learning curve and future programmers may not appreciate a less-than-straightforward approach given that there are simpler alternatives. 正则表达式有一个学习曲线,如果有更简单的选择,将来的程序员可能不会喜欢这种不那么简单的方法。

if you want to use regex, then you can use the Regex.Matches to check the count. 如果要使用正则表达式,则可以使用Regex.Matches来检查计数。

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

Several people have given examples to test for exactly 2 but here's an example to test for at least 2 periods. 有几个人给出的例子来测试正好 2但这里有一个例子来测试至少 2个周期。 You could actually easily modify this to test for exactly 2 if you wanted to too. 实际上,如果您愿意,也可以轻松修改此值以测试2个准确值。

 (.*\..*){2}

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

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