正则表达式删除某个字符之后的所有内容(注释)
我有一个正则表达式,用于删除特定字符(分号)之后的所有内容。
var regex = new Regex(@";(.*)", RegexOptions.Singleline);
tb.Text = regex.Replace(tb.Text, "");
它似乎工作正常,但有时它会删除文本框的整个文本。例如,所有这些代码都被删除:
;fgkdfgdfgd
;dfgdfkghdfgdf
;sdgfsdfsdfsdf
;dfgdfgdfg
#dont remove this ;fgdfgdfg
“#dont remove this”应该保持不变,因为它不在分号之后,但事实并非如此?我的正则表达式有问题吗?
这个想法是删除或修剪文件中的所有注释。
I have a regex which I am using to remove everything after a specific character, semi-colon.
var regex = new Regex(@";(.*)", RegexOptions.Singleline);
tb.Text = regex.Replace(tb.Text, "");
It seems to work fine, but at times it removes the entire text of the text box. For example all of this code is removed:
;fgkdfgdfgd
;dfgdfkghdfgdf
;sdgfsdfsdfsdf
;dfgdfgdfg
#dont remove this ;fgdfgdfg
the "#dont remove this" should stay intact because it isn't after the semi-colon, but it doesn't? Is something wrong with my regex?
The idea is to remove or trim all comments from a file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(5)
问题很简单 - 您误解了 RegexOptions.SingleLine
。
SingleLine
告诉模式 .
可以匹配换行符。 在此处了解有关 RegexOptions
的更多信息< /a>.
您当前的结果是单个匹配(从第一个 ;
到整个字符串的末尾)。
您只需删除 RegexOptions.SingleLine
即可,您的模式会将每个注释匹配到行尾。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
尝试(评论后更新):
这也应该比正则表达式运行得更快......
try (UPDATE after comment):
This should run faster than the Regex too...