c# - 具有特定符号的正则表达式匹配路径

标签 c# regex

目前我有这样的字符串: "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)。这后面可以有选择地跟任意数量的 并再次进行相同的检查(一个单词和索引)。

Check it out here at regex101 .

关于c# - 具有特定符号的正则表达式匹配路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38092478/

相关文章:

c# - 正则表达式匹配但不包含

regex - guid 的正则表达式

c# - 分析期间出现未知函数 CoUninitializeE

c# - 如何将信息从一个类传递到另一个类

c# - 从配置文件强制应用程序到管理员

javascript - 在正则表达式前加上一个字符串?

c# - HttpClient : Correct order to detect encoding

c# - ASP.NET Repeater - 在 HeaderTemplate 中显示数据绑定(bind)

regex - T SQL 模式或正则表达式,以确保为 varchar 列返回的所有行都严格是字母数字

java - Java中通过正则表达式模式验证输入选项