This post assumes you're familiar with binary search, Python, regular expressions, and Nondeterministic finite automata.
If you'd like to just skip straight to the code or play around with the code, you can find it at github.com/mikelmcdaniel/regex_partitioner.
Here's a little example showing how to perfectly partition the all floating point numbers expressable within 32 characters:
$ time python3 regex_partitioner.py --partitions 10 --tolerance_ratio 0 --max
_str_len 32 "[+-]?[1-9][0-9]*\.?[0-9]*([eE][+-]?[0-9]+)?"
The regular expression '[+-]?[1-9][0-9]*\\.?[0-9]*([eE][+-]?[0-9]+)?' accepts 408805925925925925925925925925936 strings with length <= 32.
The accepted strings can be evenly split, within a 0.000000% tolerance by:
'+28.5443E06666666666666666666636': 367925333333333333333333333333343 (90.0%) strings are greater.
'+459221003892680334.62e051851782': 327044740740740740740740740740749 (80.0%) strings are greater.
'+63812718e0399999999999999999971': 286164148148148148148148148148156 (70.0%) strings are greater.
'+81703281.8575270512641316111049': 245283555555555555555555555555562 (60.0%) strings are greater.
'-1': 204402962962962962962962962962968 (50.0%) strings are greater.
'-28.5443E06666666666666666666636': 163522370370370370370370370370375 (40.0%) strings are greater.
'-459221003892680334.62e051851782': 122641777777777777777777777777781 (30.0%) strings are greater.
'-63812718e0399999999999999999971': 81761185185185185185185185185188 (20.0%) strings are greater.
'-81703281.8575270512641316111049': 40880592592592592592592592592594 (10.0%) strings are greater.
real 0m3.665s
user 0m3.652s
sys 0m0.013s
And here's an NFA for that same regex:
graph LR
n0("0S")
n1("1")
n2("2S")
n3("3")
n4("4")
n5("5")
n6("6")
n7("7")
n8("8")
n9("9")
n10("10")
n11("11")
n12("12")
n13("13")
n14("14")
n15("15")
n16("16")
n17("17")
n18("18")
n19("19")
n20("20")
n21("21")
n22("22A")
n23("23A")
n24("24")
n25("25A")
n26("26")
n0 -- "+" --> n1
n0 -- "-" --> n1
n1 -- "ε" --> n3
n2 -- "ε" --> n3
n3 -- "1" --> n4
n3 -- "2" --> n4
n3 -- "3" --> n4
n3 -- "4" --> n4
n3 -- "5" --> n4
n3 -- "6" --> n4
n3 -- "7" --> n4
n3 -- "8" --> n4
n3 -- "9" --> n4
n4 -- "ε" --> n5
n5 -- "0" --> n6
n5 -- "1" --> n6
n5 -- "2" --> n6
n5 -- "3" --> n6
n5 -- "4" --> n6
n5 -- "5" --> n6
n5 -- "6" --> n6
n5 -- "7" --> n6
n5 -- "8" --> n6
n5 -- "9" --> n6
n5 -- "ε" --> n11
n6 -- "ε" --> n11
n6 -- "ε" --> n7
n7 -- "ε" --> n5
n8 -- "." --> n9
n9 -- "ε" --> n12
n10 -- "ε" --> n12
n11 -- "ε" --> n8
n11 -- "ε" --> n10
n12 -- "0" --> n13
n12 -- "1" --> n13
n12 -- "2" --> n13
n12 -- "3" --> n13
n12 -- "4" --> n13
n12 -- "5" --> n13
n12 -- "6" --> n13
n12 -- "7" --> n13
n12 -- "8" --> n13
n12 -- "9" --> n13
n12 -- "ε" --> n26
n13 -- "ε" --> n26
n13 -- "ε" --> n14
n14 -- "ε" --> n12
n15 -- "e" --> n16
n15 -- "E" --> n16
n16 -- "ε" --> n17
n16 -- "ε" --> n19
n17 -- "+" --> n18
n17 -- "-" --> n18
n18 -- "ε" --> n20
n19 -- "ε" --> n20
n20 -- "0" --> n21
n20 -- "1" --> n21
n20 -- "2" --> n21
n20 -- "3" --> n21
n20 -- "4" --> n21
n20 -- "5" --> n21
n20 -- "6" --> n21
n20 -- "7" --> n21
n20 -- "8" --> n21
n20 -- "9" --> n21
n21 -- "ε" --> n22
n22 -- "0" --> n23
n22 -- "1" --> n23
n22 -- "2" --> n23
n22 -- "3" --> n23
n22 -- "4" --> n23
n22 -- "5" --> n23
n22 -- "6" --> n23
n22 -- "7" --> n23
n22 -- "8" --> n23
n22 -- "9" --> n23
n23 -- "ε" --> n24
n24 -- "ε" --> n22
n26 -- "ε" --> n25
n26 -- "ε" --> n15
Over 10 years ago, we had a little puzzle problem at work: certain groups of globally distributed database tables shared the same key-space, which could easily be defined by a regular expression. For example, maybe the key-space for users is all strings matched by the regular expression user-[0-9]+ or U[0-9a-f]{20} or (id|test)[A-Z]+. Some tables are very small and get very little traffic so they don't need to be split up and a single server could handle all the traffic. Some tables are very large and get large amounts of traffic so they need to be split across many servers. The issue was that tables would get split automatically as needed, so as long as a new table didn't grow too quickly, there would be no problem. Unfortunately, sometimes a new table would be created and suddenly get a lot of traffic.
Some obvious practical solutions are to ramp up traffic slowly, pre-split the new table based on how an existing tables is split, add columns to an existing table instead of creating a new table and so on... I won't say what solution was used. However, I will say that a ridiculously impractical but interesting academic solution that was not used was to take the regular expression that defined the key-space and a number of desired splits, then output strings that could be used to split the key-space.
For example, user-[0-9]+ accepts strings like "user-000" and "user-123456". If you wanted 2 equally sized partitions, then you would split on "user-5" because 1/2 of all strings accepted are less than (or equal) "user-5" and 1/2 are greater. If you wanted 5 equally sized partitions, you'd split on "user-2", "user-4", and so on.
The main limitation of my solution is that it doesn't handle all strings a regex accepts but it does allow you to set an arbitrarily high limit on the length of strings that are checked.
Let's use regex = "id[0-9]+" as an example and say we want to find a partition string that has 1/3 plus-or-minus 1% of all strings up to a maximum length (max_len) of 5 accepted by regex less than our partition string.
In that example, the alphabet (in sorted order) is alphabet = "0123456789di" and has 12 characters.
max_len)lower_bound to ""upper_bound to max(alphabet) * max_len, e.g. "iiiii"mid: the string (approximately) in the middle of lower_bound and upper_boundregex are less than/equal/greater than midmid is within our range (1/3 +- 1% of all accepted strings) then we return midlower_bound or upper_bound and repeatSo there are a lot of high-level steps that aren't builtin to most languages. How do calculate a string that is the "mid"-point between lower_bound and upper_bound? How do you identify how many strings regex accepts up to a max_len that are less than (or greater than or equal to) mid? Let's solve these one by one, starting with the easier ones.
mid stringIf regex = "id[0-9]+" then the sorted alphabet = "0123456789di" because the only possible characters are i, d, and 0 thru 9. The sorting order here is based on ASCII/Unicode, as you might expect.
Since len(alphabet) == 12, we can think of any string of exactly length n in that alphabet as being in base 12, so a string like. If n = 3, then the string "000" is 0 and "52i" is $5 * 12^2 + 2 * 12 + 11 = 755$.
This isn't quite what we want because we want to be able to convert any string up to max_len into a number not just strings of exactly length n.
max_lenThe number of strings/sequences of exactly length n is just len(alphabet) ** n. So the number of strings up to max_len is sum(len(alphabet) ** n for n in range(max_len + 1)) which simplifies to (n ** (max_len + 1) - 1) // (n - 1)
def num_seqs_with_max_len(alphabet_size: int, max_len: int) -> int:
return (alphabet_size ** (max_len + 1) - 1) // (alphabet_size - 1)
Let's briefly consider an alphabet with just 2 letters "ab" and only strings/sequences up to 2 letters long. The full list would look like this (once we implement num_to_seq):
alphabet = "abc"
max_len = 2
inverse_alphabet = {v: k for k, v in enumerate(alphabet)}
print("| num | seq |")
print("|-----|-----|")
for i in range(num_seqs_with_max_len(len(alphabet), max_len)):
print(f"| {i:^3d} | {''.join(num_to_seq(i, alphabet, max_len)):3s} |")
| num | seq |
|---|---|
| 0 | |
| 1 | a |
| 2 | aa |
| 3 | ab |
| 4 | ac |
| 5 | b |
| 6 | ba |
| 7 | bb |
| 8 | bc |
| 9 | c |
| 10 | ca |
| 11 | cb |
| 12 | cc |
Notice how there is 1 empty string and "a" is 1. Also note that there are 4 sequences of length 0 or 1 and therefore the string "b" is 4 more than "a" and "c" is 4 more than "b".
In general, the larger max_len is, the bigger difference we see between "a" and "b" or "b" and "c"... in fact the difference is num_seqs_with_max_len(len(alphabet), max_len - 1). This property is recursive: Every character, c, at index i in a string adds 1 + inverse_alphabet[c] * num_seqs_with_max_len(len(alphabet), max_len - i - 1) to the number for that string.
In our example, the first character (at index 0) adds 4 and the second character adds 1.
# Note: inverse_alphabet = {v: k for k, v in enumerate(alphabet)}
def num_to_seq(num: int, alphabet: Sequence[str], max_len: int) -> Iterator[str]:
num = int(num)
len_seqs_less = max_len - 1
while num:
num_seqs_less = num_seqs_with_max_len(len(alphabet), len_seqs_less)
yield alphabet[(num - 1) // num_seqs_less]
num = (num - 1) % num_seqs_less
len_seqs_less -= 1
def seq_to_num(seq: Iterable[str], inverse_alphabet: dict[str, int], max_len: int) -> int:
len_seq_remaining = max_len - 1
num = 0
for c in seq:
num_seqs_less = num_seqs_with_max_len(len(inverse_alphabet), len_seq_remaining)
num += 1 + inverse_alphabet[c] * num_seqs_less
len_seq_remaining -= 1
return num
Now we can calculate mid like this:
alphabet = "0123456789di"
max_len = 5
inverse_alphabet = {v: k for k, v in enumerate(alphabet)}
lower_bound = ""
upper_bound = max(alphabet) * max_len
low_num = seq_to_num(lower_bound, inverse_alphabet, max_len)
high_num = seq_to_num(upper_bound, inverse_alphabet, max_len)
mid_num = (low_num + high_num) // 2
mid = "".join(num_to_seq(mid_num, alphabet, max_len))
print(f"({upper_bound!r} - {lower_bound!r}) // 2 == {mid!r}")
print(f"({high_num} - {low_num}) // 2 == {mid_num}")
('iiiii' - '') // 2 == '5iiii'
(271452 - 0) // 2 == 135726
regex acceptsAt it's core, a regular expression supports 4 operations: matching a single character, concatenation, matching any of (also known as "or"), and arbitrarily repeated matches.
For example, a is a single character match, ab is a concatenated with b, ab|c is matching ab or c, and (ab|c)* matches any number of ab|c including 0. All other operations boil down to those 4. For example, ab? is the same as a(|b), x(yz){2} is the same as xyzyz, [0-3] is the same as 0|1|2|3, and a+ is the same as aa*.
id[0-9]+ is the same as id(0|1|2|3|4|5|6|7|8|9)(0|1|2|3|4|5|6|7|8|9)*
regex to NFAregex_str = "id[0-9]+"
nfa = regex_str_to_re(regex_str).as_nfa()
print(nfa.mermaid_str())
graph LR
n0("0S")
n1("1")
n2("2")
n3("3")
n4("4")
n5("5")
n6("6A")
n7("7A")
n8("8")
n0 -- "i" --> n1
n1 -- "ε" --> n2
n2 -- "d" --> n3
n3 -- "ε" --> n4
n4 -- "0" --> n5
n4 -- "1" --> n5
n4 -- "2" --> n5
n4 -- "3" --> n5
n4 -- "4" --> n5
n4 -- "5" --> n5
n4 -- "6" --> n5
n4 -- "7" --> n5
n4 -- "8" --> n5
n4 -- "9" --> n5
n5 -- "ε" --> n6
n6 -- "0" --> n7
n6 -- "1" --> n7
n6 -- "2" --> n7
n6 -- "3" --> n7
n6 -- "4" --> n7
n6 -- "5" --> n7
n6 -- "6" --> n7
n6 -- "7" --> n7
n6 -- "8" --> n7
n6 -- "9" --> n7
n7 -- "ε" --> n8
n8 -- "ε" --> n6
The NFA above is not the simplest version it could be for the regular expression id[0-9]+ but it will suffice. The nodes are numbered for convenience. Nodes with "S" are the 'starting' nodes and nodes with "A" are the accepting nodes.
For example, to tell if this NFA above accepts "id123"
To turn a regex into an NFA, we need to support the '4 regular expression operations' mentioned earlier.
Have a start node connect an accept node via a transition/edge for that character.
a
graph LR
n0("0S")
n1("1A")
n0 -- "a" --> n1
b
graph LR
n2("2S")
n3("3A")
n2 -- "b" --> n3
Take the 2 NFAs and add an epsilon edge from all of the first NFA's accepting nodes to the second NFA's start nodes. Mark the first NFA's accepting nodes as non-accepting nodes. Mark second NFA's starting nodes as non-starting nodes.
ab
graph LR
n0("0S")
n1("1")
n2("2")
n3("3A")
n0 -- "a" --> n1
n1 -- "ε" --> n2
n2 -- "b" --> n3
or more compactly:
graph LR
n0("0S")
n1("1")
n2("2A")
n0 -- "a" --> n1
n1 -- "b" --> n2
Do... basically nothing:
a|b
graph LR
n0("0S")
n1("1A")
n0 -- "a" --> n1
n2("2S")
n3("3A")
n2 -- "b" --> n3
or more compactly:
graph LR
n0("0S")
n1("1A")
n0 -- "a" --> n1
n0 -- "b" --> n1
Add an epsilon edge from all accepting nodes to all starting nodes.
a*
graph LR
n0("0S")
n1("1A")
n0 -- "a" --> n1
n1 -- "ε" --> n0
max_len)I think this is easiest to understand 1 character at a time. How many 0-length strings does an NFA accept? If any of the starting states are also accepting states, then the NFA accepts 1 otherwise it accepts 0.
What about single character strings? Start at the start nodes and for each character, see if any of the starting nodes have a transition/edge to an accepting node.
What about longer strings? Keep track of how many strings are in a given set of states, starting with the 1 empty string in the set of all start states. Then for each character in the alphabet, see what the next set of states is. For each pair of "current" states and "next" states, add the counts associated with the "current" states to the "next" states.
class NFA:
# ...
def num_accepts(self, max_len: int) -> tuple[int, int, int]:
current_counts: dict[frozenset[int], int] = collections.defaultdict(int)
next_counts: dict[frozenset[int], int] = collections.defaultdict(int)
current_counts[frozenset(self.start_nodes)] = 1
num_accepted = int(self.accepts(""))
for _ in range(max_len):
for nodes, count in current_counts.items():
for element in self.possible_transitions(nodes):
next_nodes = frozenset(self.next_nodes(nodes, element))
next_counts[next_nodes] += count
num_accepted += self._sum_tables(next_counts)
current_counts, next_counts = next_counts, collections.defaultdict(int)
return num_accepted
mid (up to max_len)We can use a modified version of the NFA.num_accepts code that separately keeps track of how many strings are less than, greater than, or equal to the bound (so far) as we process it one character at a time. Here's what that looks like:
class NFA(object):
# ...
def num_accepts(self, max_len: int, bound: Sequence[str] = ()) -> tuple[int, int, int]:
lt1: dict[frozenset[int], int] = collections.defaultdict(int)
lt2: dict[frozenset[int], int] = collections.defaultdict(int)
eq1: dict[frozenset[int], int] = collections.defaultdict(int)
eq2: dict[frozenset[int], int] = collections.defaultdict(int)
gt1: dict[frozenset[int], int] = collections.defaultdict(int)
gt2: dict[frozenset[int], int] = collections.defaultdict(int)
eq1[frozenset(self.start_nodes)] = 1
num_accepted_le = int(self.accepts(""))
num_accepted_gt = 0
for c in itertools.islice(itertools.chain(bound, itertools.repeat(None)), 0, max_len):
for nodes, count in lt1.items():
for element in self.possible_transitions(nodes):
next_nodes = frozenset(self.next_nodes(nodes, element))
lt2[next_nodes] += count
for nodes, count in eq1.items():
for element in self.possible_transitions(nodes):
next_nodes = frozenset(self.next_nodes(nodes, element))
if c is None or (element is not None and element > c):
gt2[next_nodes] += count
elif element == c:
eq2[next_nodes] += count
else:
lt2[next_nodes] += count
for nodes, count in gt1.items():
for element in self.possible_transitions(nodes):
next_nodes = frozenset(self.next_nodes(nodes, element))
gt2[next_nodes] += count
num_accepted_le += self._sum_tables(eq2)
num_accepted_le += self._sum_tables(lt2)
num_accepted_gt += self._sum_tables(gt2)
lt1, lt2 = lt2, collections.defaultdict(int)
eq1, eq2 = eq2, collections.defaultdict(int)
gt1, gt2 = gt2, collections.defaultdict(int)
num_accepted_eq = int(len(bound) <= max_len and self.accepts(bound))
return num_accepted_le - num_accepted_eq, num_accepted_eq, num_accepted_gt
COMMENTS
You can comment on this post by replying to infosec.exchange/@mikelmcdaniel/117630473285359285 on Mastodon.
Don't have a Mastodon account? JoinMastodon.org.