正则表达式 - 正确的模式

时间:2017-08-22 13:48:36

标签: c# regex

我想问你如何为下面的代码创建一个模式,找到所有使用字符" Z"并且在有一个数字和字符" _"之后,例如Z133.88_OP0_WELDAIR_FINISH_WALLS。 这些操作可能就像这样:

G_ZLEVEL_PROFILE_0
ZTEST_OP0_WELDAIR_FINISH_WALLS
Z133.88_OP0_WELDAIR_FINISH_WALLS
Z130.88_OP0_WELDAIR_FINISH_WALLS
Z127.88_OP0_WELDAIR_FINISH_WALLS
Z133.88_OP1_COOLING_FINISH_WALLS
Z130.88_OP1_COOLING_FINISH_WALLS
Z127.88_OP1_COOLING_FINISH_WALLS

我需要它只匹配操作

Z130.88_OP0_WELDAIR_FINISH_WALLS
Z130.88_OP1_COOLING_FINISH_WALLS
Z127.88_OP0_WELDAIR_FINISH_WALLS
Z127.88_OP1_COOLING_FINISH_WALLS
Z133.88_OP0_WELDAIR_FINISH_WALLS
Z133.88_OP1_COOLING_FINISH_WALLS

代码:

pattern = @"(Z\d*)";

foreach (NXOpen.CAM.Operation operation in operations)
{
    Match match = Regex.Match(operation.Name, pattern);
    if (match.Success)
    {
          addToCamOperationGroupList(operationName: operation.Name, folderName: match.Groups[1].Value);
    }
}

3 个答案:

答案 0 :(得分:4)

\bZ[0-9\.]+_

\bZ[0-9\.]+_\S*

(获取全名)

答案 1 :(得分:4)

试试这个:

pattern = @"(^Z([\d\.]*_)\S*)";

编辑:已更新,仅匹配每行的开头。测试here

答案 2 :(得分:3)

尝试以下模式

  

^(Z[\d.]+\_\S*)$

您可以对其进行验证here