正则表达式不匹配字符串c#

问题描述 投票:0回答:1
string val = "VFC - [C:\study\Run20315.5000]"
string pattern = "VFC - *C:\\study\\Rund.*"

我写了下面的表达,但它变得虚假。

bool Match= Regex.IsMatch(val, pattern)
c# regex
1个回答
4
投票

您忘记了方括号,如果您计划匹配数字并且反斜杠必须加倍 - 或更好 - 使用逐字字符串文字,则d丢失之前的反斜杠。另外,请注意*是一个量词,使其前面的模式匹配0次或更多次。如果需要匹配两个模式之间的任意文本,请使用.*.*?,如果有换行符,请使用RegexOptions.Singleline编译模式:

string pattern = @"VFC - .*C:\\study\\Run\d";
bool Match= Regex.IsMatch(val, pattern, RegexOptions.Singleline);

查看.NET regex demoRegulex graph

enter image description here

细节

  • VFC - - 文字VFC - 子串
  • .* - 尽可能多的零个或多个字符
  • C:\\study\\Run - 一个C:\study\Run子串
  • \d - 一个数字。
© www.soinside.com 2019 - 2024. All rights reserved.