Image

Imageasmor wrote in Imagejavascript

Here's a question to all you RegEx gurus out there.

I've got a JavaScript dice roller that I made many years ago when I was first learning JS and have been keeping updated as new ideas for features hit me. It's specifically meant for people playing RPGs, like D&D.

Now, I'd like to change it so that instead of having to fill in as many as 4 boxes to specify the custom die rolls, you can just type in a string like "Move Silently:1d20+4".

I've tried to do a regex before for just the 1d20+4 part, and had limited success, but to be totally frank regular expressions give me a headache. I was hoping someone here would be willing to help me!

Format:

Label:XdY+/-Z

Where:

All white space is ignored. I.e. 1d20+4 is the same as 1 d 20 + 4.

Label is optional and can consist of anything. If it is present, a colon must be there. Otherwise there cannot be a colon.

x is optional. If present, it must be an integer.

d can be upper or lower case.

y is mandatory. It is an integer.

The + or - will only be present and will always be present if Z if specified.

Z is optional. If present, it must be an integer.

Oh, and last but certainly not least, is there anything special I need to know about implementing the RegEx? I want to be sure that the entire string validates, but I've seen before how if I typed, say, R2-D2, it would validate because D2 is a valid pattern according to my above rules.

Thanks!