简体   繁体   English

使用 C# 正则表达式替换字符串中的字符

[英]Replace a character inside a string using C# Regex

I would like to know how to replace , characters inside array brackets [] with another character, say .我想知道如何用另一个字符替换,数组括号[]内的字符,比如. . . The string expression I have is below:我的字符串表达式如下:

Attributes["412324 - PENNDOT I-95", "Category"].Value, Attributes["412324 - PENNDOT I-95", "Category"].Code属性[“412324 - PENNDOT I-95”,“类别”]。值,属性[“412324 - PENNDOT I-95”,“类别”]。代码

The expected output should be:预期的 output 应该是:

Attributes["412324 - PENNDOT I-95".属性[“412324 - PENNDOT I-95”。 "Category"].Value, Attributes["412324 - PENNDOT I-95". “类别”]. 值,属性 [“412324 - PENNDOT I-95”。 "Category"].Code “类别”].代码

var regex = new Regex(@"(?<=\[[^\[\]]*),(?=[^\[\]]*\])");
return regex.Replace(<your sample string>, ".");

Within the regex pattern, to the left of the , is a positive lookbehind zero-width assertion that means there must be a [ and then zero or more characters that are neither [ nor ] leading up to the comma.在正则表达式模式中,在 的左侧,是一个积极的后视零宽度断言,这意味着必须有一个[ ,然后是零个或多个字符,这些字符既不是[也不是]导致逗号。

After the comma, a positive lookahead zero-width assertion that means there can be zero or more characters that are neither [ nor ] then there must be a closing ] .在逗号之后,一个积极的前瞻零宽度断言,这意味着可以有零个或多个既不是[也不是]的字符,那么必须有一个关闭的]

Zero-width assertions mean that the pattern must precede or follow the matched text, but are not part of the match.零宽度断言意味着模式必须在匹配文本之前或之后,但不是匹配的一部分。 Since we are only matching the , our replacement is just the .因为我们只匹配,所以我们的替换只是.

if it's always in this sheme, then faster would be String.Replace:如果它总是在这个 sheme 中,那么 String.Replace 会更快:

string sin = "Attributes["412324 - PENNDOT I-95", "Category"].Value, Attributes["412324 - PENNDOT I-95", "Category"].Code";
string sout = sin.Replace("\", \"","\". \"");

you can do the same with RegEx, but it would be slower and still it can break if the input string changes it's structure你可以用 RegEx 做同样的事情,但它会更慢并且如果输入字符串改变它的结构它仍然会中断

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

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