开发者

regex problem C#

开发者 https://www.devze.com 2023-03-22 20:36 出处:网络
const string strRegex = @\"(?<city_country>.+) (cca|ca.|ungefähr) (?<price>[\\d.,]+) (eur)?\";
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);
           开发者_如何学JAVA }
            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." is 2 times. Why? i do not use + or ?


As with previous topic it gets into city_country group. Try to replace (?<city_country>.+) with (?<city_country>[^.]+). It will match everything except .. I guess your city_country couldn't have dots inside?


. (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)?"
0

精彩评论

暂无评论...
验证码 换一张
取 消