正则表达式 - 在线任何地方的负面回顾 [英] Regex - negative look-behind anywhere on line

查看:54
本文介绍了正则表达式 - 在线任何地方的负面回顾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当同一行上没有特定字符之前,我如何匹配模式?

How do I match a pattern only if there isn't a specific character before it on the same line?

我有以下正则表达式代码:

I have the following regex code:

pattern = @"(?<=^|[\s.(<;])(?<!//)(" + Regex.Escape(keyword) + @")(?=[\s.(>])";
replacement = "<span style='" + keywordStyle + "'>$1</span>";
code = Regex.Replace(code, pattern, replacement);

我想添加一个条件,以便仅在同一行前面没有 2 个斜杠时才匹配(C# 注释).

I would like to add a criteria to only match if there aren't 2 slashes before it on the same line (C# comment).

我玩弄了它,并修改了模式:

I played around with it, and modified the pattern:

pattern = @"(?<!\/\/)(?<=^|[\s.(<;])(?<!//)(" + Regex.Escape(keyword) + @")(?=[\s.(>])";

但显然这仅在 2 个斜杠是关键字就在之前的 2 个字符时才有效.

But apparently this only works if the 2 slashes are 2 characters right before the keyword.

所以这个模式不会匹配//foreach",但会匹配//foreach".

So this pattern wouldn't match "//foreach", but would match "// foreach".

在这种情况下可以使用否定后视吗,或者除了否定后视之外,我可以通过其他方式实现吗?

Can negative look-behinds be used in this case, or can I accomplish this some other way, besides negative look-behinds?

谢谢.

我想我还不够清楚.重申我的问题:

Guess I wasn't clear enough. To reiterate my problem:

我正在研究语法高亮,我需要找到 c# 关键字的匹配项,例如foreach".但是,我还需要考虑由 2 个斜线定义的注释.我不想匹配关键字foreach",如果它是评论的一部分(在同一行之前任何位置的 2 个斜线.

I'm working on syntax highlighting, and I need to find matches for c# keywords, like "foreach". However, I also need to take into account comments, which are defined by 2 slashes. I don't want to match the keyword "foreach" if it is part of a comment (2 slashes anywhere before it on the same line.

在这种情况下,否定的lookbehind 对我没有帮助,因为斜杠不一定就在关键字之前,例如//some text foreach" - 我不希望这个 foreach 匹配.

The negative lookbehind doesn't help me in this case because the slashes will not necessarily be right before the keyword, for example "// some text foreach" - I don't want this foreach to match.

所以,我的问题是:如何修改我的模式以仅在同一行上没有 2 个斜杠之前的任何位置时才匹配?

So again, my question is: How can modify my pattern to only match if 2 slashes aren't anywhere before it on the same line?

希望我的问题现在清楚了.

Hope my question is clear now.

推荐答案

稍微简化一下你的正则表达式模式,下面呢?它利用//"上的非贪婪匹配加上其后的 0 个或多个字符.

Simplifying your regex pattern a bit, what about the following? It makes use of the non-greedy match on "//" plus 0 or more characters thereafter.

(?<!//.*?)(?<Keyword>foreach)

这篇关于正则表达式 - 在线任何地方的负面回顾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆