简体   繁体   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)

while "Agadir ca. 600" is false but "Agadir ca. 600 eur" is true.虽然“Agadir ca. 600”是假的,但“Agadir ca. 600 eur”是真的。 "eur" is optional but "Agadir ca. 600" is false? “eur”是可选的,但“Agadir ca. 600”是假的? Why?为什么?

Enclose eur in parenthesis, like so (eur)?eur括在括号中,像这样(eur)? . .

? matches the preceding character zero or one times.匹配前面的字符零次或一次。 By enclosing it in the parens, it will match the whole word.通过将其括在括号中,它将匹配整个单词。

Also, maybe it is matching the last space before (eur)?另外,也许它与(eur)? . . Try this:尝试这个:

@"(?<city_country>[^.]+) (cca|ca.|ungefähr) (?<price>[\d.,]+)(\seur)?"

Notice, I removed the last white space and added \s , which matches any white space including space, tab, form-feed, etc.请注意,我删除了最后一个空格并添加了\s ,它匹配任何空格,包括空格、制表符、换页符等。

I think you should write (eur)?我认为你应该写(eur)? instead of eur?而不是eur? . . Ie place the Space即放置空间before also inside the parenthesis之前也在括号内

Using (eur)?使用(欧元)? instead of eur?而不是欧元? should solve the problem.应该解决问题。

best way would be @"(?<city_country>[^.]+) (cca|ca.|ungefähr) (?<price>[\d.,]+)\s*(\seur)?") putting space only inside like ( eur) would not match something like "Agadir ca. 600 "最好的方法是@"(?<city_country>[^.]+) (cca|ca.|ungefähr) (?<price>[\d.,]+)\s*(\seur)?")放置空间只有像(eur)里面的东西不会匹配像“Agadir ca. 600”这样的东西

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

OR

@"(?<city_country>[^.]+) (cca|ca.|ungefähr) (?<price>[\d.,]+)(\seur)?"

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

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