Skip to content
Advertisement

Validate an alphanumeric string that contains a fixed amount of non-consecutive periods

I have a string that looks like that "----.-------.-----.---". Here ---- is any substring of random length, . is the separator and the string can have a predetermined number of separator that I can dynamically change.

How can I use regex to validate that a string new_string matches this pattern?

I found some solution online, but none account for a random length substring and a dynamic number of separator.

Advertisement

Answer

Use in operator but try to avoid str.count is possible, as str.split can also be used to account for this, and IIUC it does the same thing under the hood in any case, so probably worth it to eliminate what could be a duplicate iteration in our case.

Added my timings below just to double check this:

JavaScript

Note that, apparently even all() times can be slightly improved, by instead having it like:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement