문제

I'm working with a syntax highlighting control and I have to specify all of the highlighted stuff with Regex. I've completed everything else (keywords, functions, strings, comments, etc.) already but I can't come up with a good rule for magic numbers. I'm using it for a Lua text editor if that helps at all.

I'm currently using \d+ to detect the digits but the problem is that I end up with things like this:

enter image description here

As you can see, my variable names are also getting parts of them highlighted.

Does anybody know of a way to make this particular rule work correctly?

도움이 되었습니까?

해결책

You don't want it to match within a name, so add a word boundary: \b\d+\b.

For floats, there could be a fractional part: \b\d+(?:\.\d+)?\b.

For floats, there could also be an exponent: \b\d+(?:\.\d+)?(?:[Ee][+\-]?\d+)\b.

다른 팁

I'd say keep it simple when it comes to regex (i.e only write what you need, and no more). The following will match group 2 to floats and ints that are being assigned:

(=\s*)([\d|\.]+)(\s*;)
  • Group 1: Context starts after '=' sign, accounting for any extra white space (the \s*).
  • Group 2: Will match against 1 or more digits (the \d) or periods (the .).
  • Group 3: Context ends at the ';', account for any extra white space before it (the \s*).

Hope that helps.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top