可以测试字符串是否为有效 Firebase 密钥的正则表达式是什么?

What would be a regular expression that can test if a string is a valid Firebase key?

我正在编写一个应用程序,允许用户输入将作为键存储在 Firebase 中的值。

Firebase 密钥要求:

max size - 768 bytes
cannot contain . $ # [ ] / or ASCII control characters 0-31 or 127
allows single spaces, but not double or more spaces

如何将其表达为正则表达式?

假设 1 个字节 = 1 个字符,并且由于您提到了 ASCII,因此假设有效字符是 ASCII 字符 32 到 126

"Match any of these allowed characters, exactly 768 times":

[ !"%&'()*+\,\-\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abcdefghijklmnopqrstuvwxyz{|}]{768}

https://regex101.com/r/lQ2gJ4/2

编辑

那没有用,因为我错过了阻止连续空格的需要。新建议,基本模式为:

# a space, not followed by a space
# or a character not followed by a double-space.
# This pattern, matched n times, locking the start and end of the string.

^( (?! )|[a](?!  )){5}$

但是,当我将完整的字符集替换为...

^( (?! )|[ !"%&'()*+\,\-\/0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ\^_`abcdefghijklmnopqrstuvwxyz{|}](?!  )){1,768}$

# it breaks Regex101, saying it's too large.

注意。没有 RegEx 会容易得多:

# Python example validator

def validate(s):
    valid_chars = 'abc123...'

    if not (0 < len(s) <= 768): return False
    if '  ' in s: return False
    for char in s: if char not in valid_chars: return False

    return True

您还没有提供用例,如果这是一个具有一些复杂输入的服务器端应用程序,您可能需要更多,但一般来说,人们并不关心输入中的控制字符,因为那会是有人修补并试图破坏东西,并且会相应地被 SDK 拒绝。

所以 Firebase 团队 generally just focuses on the invalid, keyboard-producible characters:

// in JavaScript
function isValidKey(text) {
   return typeof text === 'string' && 
      text.length &&
      !text.match(/[.$\[\]#\/]/);
}

有几个例外:.value.priority.info 是 Firebase 中的有效键,但仅用于访问特殊元数据,而不是作为记录 ID。

旁注:我在文档中没有看到任何关于双空格的信息。