javascript 使用正则表达式搜索文本高亮显示,即使文本有逗号

w7t8yxp5  于 2023-04-19  发布在  Java
关注(0)|答案(2)|浏览(94)

我很难找到一个基于正则表达式的解决方案来解决一个涉及在HTML表中搜索值的问题。
在下面的屏幕截图中,名为“Amount”的列可能在数字之间包含“,”。这是我们的客户要求,当他们搜索“247”(使用搜索字段)时,列中的值如“2,47 ...”* 或 * 如“247”,应突出显示。
我尝试使用正则表达式来解决它,但它并没有像预期的那样工作:

const regex = new RegExp(
  searchTerm
  ?.toString()
  .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
  .replace(/\s+/g, "|") + ",?",
  "gi"
);

如何在前面的例子中突出显示“2,47”?

const regex = new RegExp(
  247
  ?.toString()
  .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
  .replace(/\s+/g, "|") + ",?",
  "gi"
);

console.log('247','247'.match(regex))
console.log('2,47','2,47'.match(regex))
console.log('2.47','2.47'.match(regex))
vmdwslir

vmdwslir1#

从你的说明中,我看到除了拆分字符串并在所有字符之间动态插入一个可选的,?之外没有其他选择。
感谢Markalex:更干净的版本,,?现在只在数字之间添加。这样,它可以在转义特殊字符后完成,并且不需要可能影响鲁棒性的黑客技巧。
您也不需要插入最后一个,?,il将没有任何效果

const regex = new RegExp(
  247
  ?.toString()
  .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
  .replace(/(?<=\d)(?=\d)/g, ",?")
  .replace(/\s+/g, "|"),
  "gi"
);

console.log('regex: ',
  247
  ?.toString()
  .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
  .replace(/(?<=\d)(?=\d)/g, ",?")
  .replace(/\s+/g, "|")
)

console.log('247','247'.match(regex))
console.log('2,47','2,47'.match(regex))
console.log('2.47','2.47'.match(regex))

const regex2 = new RegExp(
  'question?'
  ?.toString()
  .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
  .replace(/(?<=\d)(?=\d)/g, ",?")
  .replace(/\s+/g, "|"),
  "gi"
);

console.log('regex: ',
  'question?'
  ?.toString()
  .replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
  .replace(/(?<=\d)(?=\d)/g, ",?")
  .replace(/\s+/g, "|")
)

console.log('question?','question?'.match(regex2))
console.log('question','question'.match(regex2))
sq1bmfud

sq1bmfud2#

answer,似乎涵盖了主要的用例,但考虑到如果你的金额不仅是美元,但可以在英镑。这正是逻辑可能失败的地方。
一种不同的方法可以是将数量以数字的格式存储在DB中,如12345或字符串“12345”。这将使得对该数据进行查找/搜索查询非常容易和高效。
现在,为了在UI端进行格式化,如金额$XX,XXX。您可以轻松使用掩码函数。
这降低了逻辑的复杂性,并且可以很容易地根据客户的要求进行修改。

相关问题