Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C正则表达式,用于将[的出现更改为[]和]更改为[]]_C#_Regex_Select_Datarow - Fatal编程技术网

C# C正则表达式,用于将[的出现更改为[]和]更改为[]]

C# C正则表达式,用于将[的出现更改为[]和]更改为[]],c#,regex,select,datarow,C#,Regex,Select,Datarow,我有一个路径+文件名,多次包含[]。 我想做的是将[]放在每个[因此: E:\Test\Ananas[在笼子里]when[大象]laugh.png 替换成 E:\Test\Bananas[[]在笼子里[[]当[[]大象[]]大笑时[[]香蕉[[]]png 原因如下: DataRow[] tempRows = filenames.Select("File like '" + tempLogElement + "'"); 如果出现包含方括号的路径,这将崩溃。这是因为[]用于在此类“like”语句中

我有一个路径+文件名,多次包含[]。 我想做的是将[]放在每个[因此:

E:\Test\Ananas[在笼子里]when[大象]laugh.png

替换成

E:\Test\Bananas[[]在笼子里[[]当[[]大象[]]大笑时[[]香蕉[[]]png

原因如下:

DataRow[] tempRows = filenames.Select("File like '" + tempLogElement + "'");
如果出现包含方括号的路径,这将崩溃。这是因为[]用于在此类“like”语句中转义*和%。避免此情况的方法是转义转义字符

我在Regex并不出色,但我在这里得到了一个许可:

Regex.Replace(tempLogElement, "(\[*\])", "[]]", RegexOptions.IgnoreCase);
这只会转义]字符,而不会转义[字符

这是行不通的:

tempLogElement.Replace("[","[[]").Replace("]","[]]")

第二次替换会把第一次替换搞砸。所以我想我必须在一次操作中使用一些可以做到这一点的东西。首先想到的是正则表达式。

为什么不使用字符串。选择

或者用一本书作为纪念

string temp = tempLogElement, replaced = "";
for (int i = 0; i < temp.Length; i++)
{
    if (temp[i] == '[') replaced += "[[]";
    else if (temp[i] == ']') replaced += "[[]";
    else replaced += temp[i];
}
-更新替换使用$1而不是匿名方法。-

尝试

Regex.Replace(tempLogElement, "\[([\w\s]*)\]", "[[]$1[]]", RegexOptions.IgnoreCase);

下面是一个简短的例子:

Regex.Replace(input, @"\[|\]", "[$0]")
这将匹配[或],并替换为包含原始字符的[…]

tempLogElement.Replace("[", "[[").Replace("]", "[]]").Replace("[[", "[[]");

嗯……你的第二次替换,将替换第一次替换中的项目!这将导致第一次替换中新插入的右方括号被第二次替换。第二次替换会把事情搞砸。所以我想我必须使用在一次操作中就完成的东西。首先想到的是Regex。是的,这是可能的。好主意:输入字符串中的括号是否总是成对匹配?或者输入字符串是否有[没有对应]?是否没有对应的…这是一个文件名,因此它可以包含任何组合。将其更改为适用于我:Regex fixString=new Regex@[^]*],RegexOptions.IgnoreCase;string test=fixString.replaceTemplageElement,m=>[[]+m.Groups[1].Value+[]];DataRow[]tempRows=filenames.SelectFile类似于“+test+”;您好,@rikitikitik,您的正则表达式与[cage]中的第一个字符串不匹配,应该更改:\[\w\s]*\]更短更甜。这正是我要找的,真聪明!我会尽量记住的:
Regex.Replace(input, @"\[|\]", "[$0]")
tempLogElement.Replace("[", "[[").Replace("]", "[]]").Replace("[[", "[[]");