转换Pythonre.sub公司到C#

2024-04-28 23:53:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从Python到C的转换

   sconvert = re.sub(r"([.$+?{}()\[\]\\])", r"\\\1", sconvert)

我找不到与这个函数等价的C#.Net来简化它。在

从Python手册

re.sub(pattern, repl, string, count=0, flags=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone. Backreferences, such as \6, are replaced with the substring matched by group 6 in the pattern.


Tags: thetoinrestringbyisit
1条回答
网友
1楼 · 发布于 2024-04-28 23:53:02

您正在寻找^{} method

Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space) by replacing them with their escape codes. This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.

sconvert = re.sub(r"([.$+?{}()\[\]\\])", r"\\\1", sconvert)代码转义[.$+?{}()\[\]\\]范围中指定的字符,以匹配它们所表示的文字字符。在

请注意,Regex.Escape也会转义空格。如果不需要,请使用自定义替换:

var input = "|^.$+?{}()[]\\-";
var escaped = Regex.Replace(input, @"[|^.$+?{}()\[\]\\-]", "\\$&");
Console.Write(escaped);
// => \|\^\.\$\+\?\{\}\(\)\[\]\\\-

我建议添加|-和{}。见IDEONE demo

相关问题 更多 >