简体   繁体   English

正则表达式模式匹配由分隔符

[英]Regex pattern match by delimiter

to get the value of gs from the below query.从以下查询中获取 gs 的值。

(2|3|4|5|6|7|8|9|10|11|gs=accountinga sdf* |gs=tax*|12|ic='38') (2|3|4|5|6|7|8|9|10|11|gs=accountinga sdf* |gs=tax*|12|ic='38')

I have tried with below pattern我试过下面的模式

(?<=gs=)(.*)([|]) (?<=gs=)(.*)([|])

But this results gs=accounting asdf* |gs=tax*|12|但这会导致gs=accounting asdf* |gs=tax*|12|

Desired output should be : accounting asdf*,tax*期望的输出应该是: accounting asdf*,tax*

is that possible with change in pattern ?这可能随着模式的变化而改变吗?

This regex will match as you want.此正则表达式将根据您的需要进行匹配。

(?<=gs=)([^|)]*)

It will also handle the case where gs is the last clause without including the closing bracket in the group.它还将处理 gs 是最后一个子句而不在组中包含右括号的情况。

I suggest 2 solutions, see their online demo .我建议 2 个解决方案,请参阅他们的在线演示

One is regex-based:一种是基于正则表达式的:

var x = "(2|3|4|5|6|7|8|9|10|11|gs=accountinga sdf* |gs=tax*|12|ic='38')";
var result = Regex.Matches(x, @"(?:^|\|)gs=([^|]*)")
    .Cast<Match>()
    .Select(p => p.Groups[1].Value)
    .ToList();
foreach (var s in result)
    Console.WriteLine(s);

NOTE that the (?:^|\\|)gs=([^|]*) pattern will only match gs= at the string beginning or after |注意(?:^|\\|)gs=([^|]*)模式只会匹配gs=开头或之后的字符串| , and then ([^|]*) will capture zero or more chars other than | , 然后([^|]*)将捕获除|之外的零个或多个字符into Group 1 that you will collect later with Select .进入第 1 组,稍后您将使用Select收集该组。 See the regex demo .请参阅正则表达式演示

Or a non-regex based, just split with |或基于非正则表达式,只需拆分| , check if the item starts with gs= , and then split with = to get the last part: , 检查项是否以gs=开头,然后用=分割得到最后一部分:

var res2 = x.Split('|')
        .Where(p => p.StartsWith("gs="))
        .Select(n => n.Split('=').LastOrDefault())
        .ToList();
    foreach (var t in res2)
        Console.WriteLine(t);

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

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