簡體   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