C# regex for assembly style hex numbers

Deadly 提交于 2019-12-23 22:19:24

问题


I'm new to regex and I want to highlight hexadecimal numbers in Assembly style. Like this:

$00
$FF
$1234
($00)
($00,x)
and even hexadecimal numbers that begin with #.

So far I wrote "$[A-Fa-f0-9]+" to see if it highlights numbers beginning with $ but it doesn't. Why? And can someone help me with what I'm doing? Thanks.


回答1:


Put a back slash before $ and your regex will work like so

\$[A-Fa-f0-9]+

$ is a valid regex character that matches with end of string. So if your pattern contains dollar then you need to escape it. See regex reference for details




回答2:


This should cover all those cases, including the cases in which you get a # instead of a $

public Regex MyRegex = new Regex(
          "^(\\()?[\\$#][0-9a-fA-F]+(,x)?(?(1)\\))[\\s]*$",
        RegexOptions.Singleline
        | RegexOptions.Compiled
        );

The unescaped sequence for the single line: ^(\()?[\$#][0-9a-fA-F]+(,x)?(?(1)\))[\s]*$

That should validate on a per-line match.

By the way, I made this regex pretty quickly using Expresso



来源:https://stackoverflow.com/questions/7857275/c-sharp-regex-for-assembly-style-hex-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!