简体   繁体   English

正则表达式问题 C#

[英]regex problem C#

const string strRegex = @"(?<city_country>.+) (cca|ca.|ungefähr) (?<price>[\d.,]+) (eur)?";
            searchQuery = RemoveSpacesFromString(searchQuery);
            Regex regex = new Regex(strRegex, RegexOptions.IgnoreCase);

            Match m = regex.Match(searchQuery);
            ComplexAdvertismentsQuery query = new ComplexAdvertismentsQuery();

            if (m.Success)
            {
                query.CityOrAreaName = m.Groups["city_country"].Value;
                query.CountryName = m.Groups["city_country"].Value;
                query.Price = Convert.ToDecimal(m.Groups["price"].Value);
            }
            else
                return null;

ca.must be for example only 1 times but the word "Agadir ca. ca. 600 eur" is also correct even if "ca."例如必须只有 1 次,但即使是“ca.”,“Agadir ca. ca. ca. 600 eur”这个词也是正确的。 is 2 times.是 2 倍。 Why?为什么? i do not use + or?我不使用 + 或?

As with previous topic it gets into city_country group.与之前的主题一样,它进入city_country组。 Try to replace (?<city_country>.+) with (?<city_country>[^.]+) .尝试将(?<city_country>.+)替换为(?<city_country>[^.]+) It will match everything except .它将匹配除. . . I guess your city_country couldn't have dots inside?我猜你的city_country里面不能有点?

. . (Dot) Mathes anything in Regex even spaces which leads to the problem (点)计算正则表达式中的任何内容,甚至导致问题的空间

So your matches are:所以你的比赛是:

  1. @"(?<city_country>.+):Agadir ca.
  2. (cca|ca.|ungefähr): ca.
  3. (?<price>[\d.,]+) (eur)?:600 eur

You need to match the city name withouth using the dot, for example something like:您需要在不使用点的情况下匹配城市名称,例如:

@"(?<city_country>[a-zA-Z]+) (cca|ca.|ungefähr) (?<price>[\d.,]+) (eur)?"

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

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