我对正则表达式几乎不熟悉。
我正在使用JsonPath和regexp编写一个杰维表达式,我想通过只匹配图书作者属性的前两个字母来找到节点
实际表达
$..book[?(@.author =~ /\A.{0}(Ni).*/)]找到我需要的
[
{
"category" : "reference",
"author" : "Nigel Rees",
"title" : "Sayings of the Century",
"price" : 8.95
}
]从…
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10}
你知道那个案子更干净吗?在实际的regexp中或者应该添加什么是不必要的?
发布于 2015-08-13 21:10:23
让我试试看。
regex /\A.{0}(Ni).*/的意思是:
\A -匹配字符串的开头.{0} -匹配任何字符,但换行符完全匹配0次(Ni) -匹配并捕获到第1组文字文本Ni.* -匹配除换行符外的0或多个字符(尽可能多)你只需检查一下是否与=~匹配。
不必要的部分是点1和2。删除\A,因为表达式在默认情况下是锚定的。删除.{0},因为它没有任何意义。
.*似乎是必要的,因为表达式应该匹配整个字符串。作为一个小小的改进,从(Ni)中删除括号,因为您没有使用任何反向引用。请注意,从逻辑的角度来看,用正则表达式捕获/存储我们已经知道的内容是没有意义的,除非有特定的用途(例如将字符串分割成数组)。
因此,使用
$..book[?(@.author =~ /Ni.*/)]请注意,添加/i修饰符也会使表达式匹配值从ni开始。
https://stackoverflow.com/questions/31991181
复制相似问题