Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top