gpt4 book ai didi

c# - 使用 String.Format 构建正则表达式 : "Input string was not in a correct format"

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:04 25 4
gpt4 key购买 nike

我正在构建文档模板引擎。在某些时候,我需要匹配 Reg Exp 组并将模板文本替换为数据库中的内容。

我最初“硬编码”了我的 RegExp,做了类似的事情:

Regex r = new Regex(@"{DocSectionToggle::(?<ColumnName>\w+)::(?<ResponseValue>.+)}\n\[\[(?<SectionContent>.+)\]\]", RegexOptions.Multiline);

抱歉:它进行组捕获,所以语法不是最漂亮的。

只是为了让事情更整洁,并且因为我想在 web.config 或其他地方保留模式,我已经将算法“进化”成类似的东西:

string _regexp_DocSectionToggle = @"{DocSectionToggle::{0}::{1}}\n\[\[{2}\]\]";

/* Reg Exp Patterns for group capture */

string _rxCol = @"(?<{ColumnName}>\w+)";
string _rxResp = @"(?<{ResponseValue}>.+)";
string _rxSectContent = @"(?<{SectionContent}>.+)";

Regex r = new Regex( string.Format(_regexp_DocSectionToggle,
_rxCol,
_rxResp,
_rxSectContent),

RegexOptions.Multiline
);

但我收到一个错误:“输入字符串的格式不正确”。

谁能告诉我为什么?这是 string.Format(...) 的限制吗?

感谢您的关注。

最佳答案

问题是您不想标记格式说明符的{}。 IIRC,你只需将它们加倍:

string _regexp_DocSectionToggle = @"{{DocSectionToggle::{0}::{1}}}\n\[\[{2}\]\]";

关于c# - 使用 String.Format 构建正则表达式 : "Input string was not in a correct format",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5219376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com