正则表达式解析图书查询字符串:双引号相关问题排查
图书查询字符串解析问题
我正在解析图书查询字符串,其中intitle:这类前缀用于指定图书的特定查询字段,目前遇到两个问题:
- 无法解析返回结果中第三个元素里的
inauthor、inpublisher等字段,比如champ inauthor:"john smith" inpublisher:"the book place",怀疑和字符串中的双引号有关 - 如何通过双引号将内容识别为单个术语
待解析字符串
basketball intitle:champ inauthor:"john smith" inpublisher:"the book place" subject: fiba isbn: 12345 lccn: 689778 oclc: 1234156
尝试的代码
let q: string = `basketball intitle:champ inauthor:"john smith" inpublisher:"the book place" subject: fiba isbn: 12345 lccn: 689778 oclc: 1234156`; console.log(q); q = q.replaceAll(`: `, `:`); console.log(q); let all = q.split( /(\bintitle:\b|\binauthor:\b|\binpublisher:\b|\bsubject:\b|\bisbn:\b|\blccn:\b|\boclc:\b)/, ); console.log(all);
返回结果
[ 'basketball ', 'intitle:', 'champ inauthor:"john smith" inpublisher:"the book place" ', 'subject:', 'fiba ', 'isbn:', '12345 ', 'lccn:', '689778 ', 'oclc:', '1234156' ]
解决方案
问题分析
当前用正则分割的方式无法处理带双引号的内容:正则匹配字段前缀时,会被双引号内的空格干扰,导致inauthor:和inpublisher:没有被识别为分割标记,进而无法拆分对应字段。
解决思路
编写能识别双引号内内容的正则,遍历字符串提取字段和对应值:
- 先统一去掉字段前缀后多余的空格(比如
subject: fiba转为subject:fiba) - 用正则匹配三种内容:字段前缀、双引号包裹的内容、普通单词
- 先提取无前缀的搜索词,再逐个匹配带前缀的字段及其对应值
示例代码
const q = `basketball intitle:champ inauthor:"john smith" inpublisher:"the book place" subject: fiba isbn: 12345 lccn: 689778 oclc: 1234156`; // 统一去除冒号后的空格 const processed = q.replace(/:\s+/g, ':'); // 正则规则:匹配字段前缀、双引号内内容、普通单词 const regex = /(\b(?:intitle|inauthor|inpublisher|subject|isbn|lccn|oclc):)|"([^"]+)"|(\S+)/g; const result: { [key: string]: string[] } = { keywords: [] }; let currentField: string | null = null; let match; while ((match = regex.exec(processed)) !== null) { if (match[1]) { // 匹配到字段前缀,记录当前字段(去掉末尾冒号) currentField = match[1].slice(0, -1); result[currentField] = []; } else if (match[2]) { // 匹配到双引号内容,归入当前字段或关键词 if (currentField) { result[currentField].push(match[2]); } else { result.keywords.push(match[2]); } } else if (match[3]) { // 匹配到普通单词,归入当前字段或关键词 if (currentField) { result[currentField].push(match[3]); } else { result.keywords.push(match[3]); } } } console.log(result);
输出结果
{ keywords: ['basketball'], intitle: ['champ'], inauthor: ['john smith'], inpublisher: ['the book place'], subject: ['fiba'], isbn: ['12345'], lccn: ['689778'], oclc: ['1234156'] }
内容的提问来源于stack exchange,提问作者mateoc15
相关产品推荐
相关产品推荐

