how to concat a variable to a regex in C# [closed]

淺唱寂寞╮ 提交于 2019-12-04 07:37:33

问题


I am trying to concat a variable to a regen in c# but it is not working

string color_id = "sdsdssd";
Match variations = Regex.Match (data, @""+color_id+"_[^\""]*\""\W\,\""sizes\""\:\s*\W.*?businessCatalogItemId"":\"")", RegexOptions.IgnoreCase);@""+color_id+"_[^\""]*\""\W\,\""sizes\""\:\s*\W.*?businessCatalogItemId"":\"")";

But the above is not working

How to concat a variable at starting element to regex in c#


回答1:


The @ identifier only affects the immediately following literal string - you need to apply it to each string that needs it:

Match variations = Regex.Match (data,color_id +                     
                                     @"_[^\""]*\""\W\,\""sizes\""\:\s*\W.*?businessCatalogItemId"":\"")", 
                                RegexOptions.IgnoreCase);



回答2:


Your code is not working because you appear to have put this into your code twice.

@""+color_id+"_[^\""]\""\W\,\""sizes\"":\s\W.*?businessCatalogItemId"":\"")"

Removing that should allow the concatenation to work.

Alternatively, you could use String.Format to make the pattern

string pattern = String.Format("@{0}_[^\""]*\""\W\,\""sizes\""\:\s*\W.*?businessCatalogItemId"":\"")", color_id)
Match variations = Regex.Match (data, pattern, RegexOptions.IgnoreCase);

In the String.Format, it will replace the {0} with color_id. You can use this to insert multiple variable into the string. Take a look at this MSDN page for more info




回答3:


In C#6.0, you can use interpolated strings:

var color_id = "sdsdssd";
var variations = 
    Regex.Matches(
        input, 
        $@"{Regex.Escape(color_id)}_[^""]*""\W,""sizes"":\s*\W.*?businessCatalogItemId"":""",
        RegexOptions.IgnoreCase
 );

The $ before a string literal makes it possible to use code inside {...} blocks, and @ makes a string literal verbatim (no escape sequences like \r or \n are recognized, they are treated as 2 symol combinations, \ and a char).

Note that the last ) is redundant and causing the pattern to become invalid.

Note that it is the best practice to escape a variable that should be treated as a literal inside the regex pattern, but if your color_id is always alphanumeric/underscore based string, you can omit that.



来源:https://stackoverflow.com/questions/38376687/how-to-concat-a-variable-to-a-regex-in-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!