目前我有这样的字符串:
"document.info.userId"
(json 属性路径)和验证它们的正则表达式模式:([\w]+\.)+[\w]+$
但似乎有这样的字符串:"document.role#0.id"
(数组的一些额外标记)并且它们有效,但我无法弄清楚哪个正则表达式要使用的模式。此索引(#0、#1.. 等)只能在点之前,不能在任何路径部分的中间。
我已经尝试过模式 ([\w#]+\.)+[\w#]+$
和 ([\w]+(#\d+)*\.)+[\w]+(#\d+)*$
但它们传递无效路径,如下所示:test.some#a.hello
应该通过:
"document.role.id"
"document.role.id.and.other.very.long.path.example"
"document.role#0.id"
"document#1.role#0.id"
"document#1.role#0#1.id"
"document#1.role#0#1.id#21" - terrible representation of array in array
不应该通过:
"document."
"document.role."
".document"
"test.some#a.hello"
"docum#ent.role.id"
"document.role.#id"
"docu#1ment.role.id"
"document.ro#0#1le.id"
最佳答案
尝试
^\w+(?:#\d+)*(?:\.\w+(?:#\d+)*)*$
它首先检查一个单词,后跟任意数量的索引 (#N
)。这后面可以有选择地跟任意数量的 。
并再次进行相同的检查(一个单词和索引)。
关于c# - 具有特定符号的正则表达式匹配路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38092478/