C# 正则表达式 - 在字符之前匹配模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1060690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:15:54  来源:igfitidea点击:

Regex - Match a Pattern Before a Character

c#regex

提问by bplus

I'm currently building a toy assembler in c# (going through The Elements Of Computing Systemsbook).

我目前正在用 c# 构建一个玩具汇编器(通过计算系统的元素书)。

I need to match a very simple pattern, I thought this would be a good time to learn some regex but I'm struggling!

我需要匹配一个非常简单的模式,我认为这是学习一些正则表达式的好时机,但我很挣扎!

In the following examples I'd just like to match the letters before the '='

在以下示例中,我只想匹配 '=' 之前的字母

M=A

M=A

D=M

D=M

MD=A

MD=A

A=D

A=D

AD=M

AD=M

AMD=A

AMD=A

I've come up with the following:

我想出了以下几点:

([A-Z]{1,3})=

However this also matches the '=' which I don't want.

但是,这也与我不想要的 '=' 匹配。

I also tried:

我也试过:

([A-Z^\=]{1,3})=

But I still have the same problem - it a matches the '=' sign as well.

但我仍然有同样的问题 - 它也匹配 '=' 符号。

I'm using this siteto test my regexes.

我正在使用这个站点来测试我的正则表达式。

Any help would be really appreciated. Thank you in advance.

任何帮助将非常感激。先感谢您。

采纳答案by RichieHindle

You need a positive lookahead assertion:

你需要一个积极的前瞻断言

([A-Z]{1,3})(?==)

回答by Conspicuous Compiler

What you want is called a zero-width, lookahead assertion. You do:

你想要的是一个零宽度的前瞻断言。你做:

(Match this and capture)(?=before this)

In your case, this would be:

在您的情况下,这将是:

([A-Z^]{1,3})(?==)

回答by Nippysaurus

The following will group everything before the "=" and everything after.

下面将对“=”之前的所有内容和之后的所有内容进行分组。

([^=]*)=([^=]*)

it reads something like this:

它是这样写的:

match any amount of characters thats not a "=", followed by a "=", then any amount of characters thats not a "=".

匹配任何数量的不是“=”的字符,后跟一个“=”,然后是任何数量的不是“=”的字符。

回答by Dinah

You can also put the equals sign in a non-capturing parans with (?: ... )

您还可以使用 (?: ... ) 将等号放在非捕获参数中

([ADM]{1,3})(?:=)

It's been a bit since I did this chapter of the book but I think that since you need both parts of the expression anyway, I did a split on the = resulting in myArray[0] == M, myArray[1] == A

自从我完成本书的这一章以来已经有一段时间了,但我认为因为无论如何你都需要表达式的两个部分,所以我对 = 进行了拆分,导致 myArray[0] == M, myArray[1] == A

回答by Tola

I needed to match every character before the '=' so I came up with this

我需要匹配 '=' 之前的每个字符,所以我想出了这个

.*(?==)=

Matches every character before '=' but not "="

匹配 '=' 之前的每个字符,但不匹配“=”