简体   繁体   中英

Regex math path with specific symbols

for this moment i have strings like this: "document.info.userId" (json property paths) and regex pattern to validate them: ([\\w]+\\.)+[\\w]+$

but there appear to be string like this: "document.role#0.id" (some extra markup for arrays) and they are valid to, but i can't figure out which regexp pattern to use. This index (#0,#1.. etc) can be only before dot, not in a middle of any path part.

I've already tried patterns ([\\w#]+\\.)+[\\w#]+$ and ([\\w]+(#\\d+)*\\.)+[\\w]+(#\\d+)*$ but they pass invalid paths like this: test.some#a.hello

Should pass:

"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

Should not pass:

"document."
"document.role."
".document"
"test.some#a.hello"
"docum#ent.role.id"
"document.role.#id"
"docu#1ment.role.id"
"document.ro#0#1le.id"

You can add an optional #[\\d] :

^([\w]+(#[\d])*\.)+[\w]+$
       ^^^^^^^^

This way, the text #N , N being an integer, can or cannot happen.

See it live with some sample input in https://regex101.com/r/mZ3mZ6/2

Taking into account all the samples you later on added:

^([\w]+(#[\d]+)*\.)+[\w]+(#[\d]+)*$

This way we also check for #N , being N any integer (not just one digit) and also allowing the last block to contain such specifier.

See it live in https://regex101.com/r/mZ3mZ6/3 passing all cases.

Try

^\w+(?:#\d+)*(?:\.\w+(?:#\d+)*)*$

It starts by checking for a word followed by any number of indexes ( #N ). This can optionally be followed by any number of . and the same check again (a word and indexes).

Check it out here at regex101 .

长期解决方案但有效:

^(\w+(?:(#[\d]+)*)?\.)(\w+(?:(#[\d]+)*)?\.)+(\w+(?:(#[\d]+)*)?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM