我将编写一个应用程序,允许用户输入需要存储在Firebase中的键和值。
Firebase键(Key)的要求:
max size - 768 bytes
cannot contain . $ # [ ] / or ASCII control characters 0-31 or 127
allows single spaces, but not double or more spaces
我该如何用正则表达式来表示这个呢?
[ !"%&'()*+\,\-\/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.
# 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
// in JavaScript
function isValidKey(text) {
return typeof text === 'string' &&
text.length &&
!text.match(/[.$\[\]#\/]/);
}
.value
、.priority
和.info
是 Firebase 中有效的键,但仅用于访问特殊元数据,而不是作为记录 ID。
^((?!\s{2}).)
,并在结尾添加\s?
,可以覆盖双倍间距。 - JStevens