0

我是正则表达式的新手。我的字符串格式如下
:1)372 万人(国家排名:第 6)(2004 年估计)
2)10000 人(2007 年估计)

我想从这两种字符串中提取人口数和时间。如何在 C# 的正则表达式中做到这一点。还是我需要编写多个正则表达式?

4

4 回答 4

3

这是一个起点:

(?<population>\d\(.\d+)?)  #capturing group named "population"
                           #that is a number, optionally followed by a
                           #decimal point and at least one number
\s*                        #followed by one or more spaces
(?<magnitude>thousand|(m|b)illion)? #optional capturing group named "magnitude"
                                    # that matches "thousand", "million", or "billion"
\s*                        #one or more whitespace characters
people                     #the literal "people"
.*                         #match any number of characters
\(                         #Find literal opening parentheses...
   (?<year>\d{4})          #...followed by a four-digit year...
\s                         #...followed by a space...
estimate\)                 #...followed by the phrase "estimate)"
\s*$                       #followed by optional whitespace
                           #and the end of the string

显示用法的简单驱动程序:

class Program
{
/// Generate test strings
static IEnumerable<string> Generator()
{
    yield return "3.72 million people (country rank: 6th) (2004 estimate)";
    yield return "10000 people (2007 estimate)";
}

public static void Main()
{
    string expression = @"
(?<population>\d(.\d+)?)  #capturing group named 'population'
                           #that is a number, optionally followed by a
                           #decimal point and at least one number
\s*                        #followed by one or more spaces
(?<magnitude>thousand|(m|b)illion)? #optional capturing group named 'magnitude'
                                    # that matches 'thousand', 'million', or 'billion'
\s*                        #one or more whitespace characters
people                     #the literal 'people'
.*                         #match any number of characters
\(                         #Find literal opening parentheses...
   (?<year>\d{4})          #...followed by a four-digit year...
\s                         #...followed by a space...
estimate\)                 #...followed by the phrase 'estimate'
\s*$                       #followed by optional whitespace
                           #and the end of the string";

    RegexOptions options = 
        RegexOptions.IgnorePatternWhitespace // allow whitespace/comments
        | RegexOptions.IgnoreCase
        | RegexOptions.ExplicitCapture; // Only capture named groups

    Regex r = new Regex(expression, options);
    foreach (var test in Generator())
    {
        Match match = r.Match(test);
        if (!match.Success)
            Console.WriteLine("Could not match {0}", test);
        else
        {
            double population = double.Parse(match.Groups["population"].Value);
            if (match.Groups["magnitude"].Success) // magnitude is optional
                                                   // but if present, need to
                                                   // multiply population
            {
                switch (match.Groups["magnitude"].Value.ToLower())
                {
                    case "thousand": population *= 1000; break;
                    case "million": population *= 1E6; break;
                    case "billion": population *= 1E9; break;
                    default: throw new FormatException("Unexpected value in magnitude group");
                }
            }
            int year = int.Parse(match.Groups["year"].Value);
            Console.WriteLine("In {0}, population was {1} people.", year, population);
        }
    }
}

输出:

In 2004, population was 3720000 people.
In 2007, population was 10000 people.
于 2012-07-14T05:25:20.027 回答
2

尝试:

(?<number>\d+.\d*)(?: million)? people(?: \(country rank: 6th\))? \((?<year>\d+) estimate\)

http://regexhero.net/tester/它给出了这个结果: 在此处输入图像描述

http://myregextester.com/index.php你得到: 在此处输入图像描述

于 2012-07-14T05:52:54.230 回答
1

如果您的目标是这种模式,请尝试下一个Regex

[population/number and text] people [some text] ([date] estimate)

正则表达式:

var match = Regex.Match(inputString, 
                        @"(?<number>[\.\d]+(\s+\w+)?)\s+people .+\((?<date>\d+)\s+estimate\)");

var population = match.Groups["number"].Value;
var date = match.Groups["date"].Value;
于 2012-07-14T05:20:06.383 回答
1

您可能需要两个正则表达式,因为您想以不同的方式处理它们。我复制粘贴了你的整个两行,包括“1)”和“2)”。这是针对人口的(开头有一个空格):

 \d+(?!\w)\.?(?=\d*)\d*

一个空格后跟一个或多个数字,如果它后面没有字母,后跟一个或零个点,仅当下一个字符是一个或多个数字,后跟数字时才有效。至于像百万/千这样的词,你必须用零替换它们。

然后是日期部分:

(?:\()\d{4}(?!\d)

匹配左括号而不记住它,如果第五件事不是数字,则后面跟着四个数字。

希望有帮助。老实说,我不太了解 c#,我在 JavaScript 中测试了这些。

编辑:其他人有更完整的答案,他们实际上是在 c# 中,去检查一下。

于 2012-07-14T05:24:14.897 回答