开发者

Regex [\S but not [[\S?

I'm trying to get matches of single bracket followed by a non-space, but not a double-bracket and non-space.

Aka:  This is ok:  [s
      This should be skipped:  [[s

I have @"\[[\S^\[]" but it isn't quite working.

Edit: To clarify a little, I'm working on a wiki parser (so it is string based - I had thought that was only what regular expressions worked on). My links start with [, but I'd like to escape [ with a double [[. The wiki already works, but开发者_JAVA百科 I'm creating a revised version that is (hopefully) easier to extend.

Here's the Handler invoke code:

foreach (Rule rule in rules)
{
    if (position + rule.Length > text.Length)
        break;
    if ((rule.PreCondition & condition) == rule.PreCondition)
    {
        if (substring.Length < rule.Length)
            substring = text.Substring(position, rule.Length);
        if (rule.Pattern.IsMatch(substring))
        {
            string previous = text.Substring(0, position);
            sb.Append(previous);
            text = text.Remove(0, position);
            position = 0;
            text = rule.Handler(new HandlerParameter(text, condition, previous));
        }
    }
}

So the BracketHandler uses the pattern to determine if we're at a bracket. My original pattern was \[\S, but that doesn't work for [[s if it is checking the [s and the last character of previous is a [. Just a heads up with my convoluted code, but at least it is posted to see.


Could use a negative lookbehind:

@"(?<!\[)\[[^[\s]"

(Wow that looks sinister, eh?...)

Edit: a potential alternative which doesn't require a lookbehind:

@"(^|[^[])\[[^[\s]"


I think the problem is that the ^ has to be at the begining of the group to indicate a negation. Why not indicate the negative group of spaces and '[' like this:

@"\[[^\s\[]"


Am I missing something here, or [^[]\[[^\s[] will work without problems?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜