正则表达式 方括号的转义

lzl124631x 2011-07-09 01:31:31
问下 C#中方括号[和]怎么转义??
我试了下[[]和[]]可以代表这两个字符
但是怀疑是不是有更好的方法~
...全文
982 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
-过客- 2011-07-09
  • 打赏
  • 举报
回复
正则中,绝大多数字符中字符组[]中都是不需要转义的
[[]这种不构成歧义的,在.NET中是支持的,但在其它语言中不一定支持,所以最好不要这样用,直接用\[转义,或者多个字符取或时,还是显式的加下转义的好,比如[\s\[]

至于2楼的问题

string pattern = "(?<=--)(.+?)(?=--)";

当然,这样就没必要用捕获组了,只不过去掉捕获组后,要用$0,而不是$1了
自由建客 2011-07-09
  • 打赏
  • 举报
回复
斜杠问题当然要注意, shell 常用单引号, C# 自然常用 @" 。
[] 本为内集或, [[] []] 并无歧义,当然可用。
诺维斯基 2011-07-09
  • 打赏
  • 举报
回复
等高手吧
liulangdeyuyu 2011-07-09
  • 打赏
  • 举报
回复
string pattern = "-(.+?)-";
lzl124631x 2011-07-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 soonfei 的回复:]

晕,转义,当然要用转义字符"\"了!!
[/Quote]

啊 突然想起来 我之前用的是“\[”这个不能代表[ 要用“\\[”或者@“\[”代表[ ~~~~我出错在这儿了
但是为什么[[]能代表[??在这里面就不需要转义

另外问:
using System;
using System.Text.RegularExpressions;

public class Example
{
public static void Demo(System.Windows.Controls.TextBlock outputBlock)
{
string pattern = "--(.+?)--";
string replacement = "($1)";
string input = "He said--decisively--that the time--whatever time it was--had come.";
foreach (Match match in Regex.Matches(input, pattern))
{
string result = match.Result(replacement);
outputBlock.Text += result + "\n";
}
}
}
// The example displays the following output:
// (decisively)
// (whatever time it was)

这是msdn的Match.Result方法中的

只是觉得以后会碰到这种问题:如果想结果是
(decisively)
(that the time)
(whatever time it was)
怎么办??
诺维斯基 2011-07-09
  • 打赏
  • 举报
回复
晕,转义,当然要用转义字符"\"了!!

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧