【问题标题】:Return specific portion of a string in specific format that includes a number[]以包含数字[]的特定格式返回字符串的特定部分
【发布时间】:2022-01-27 06:55:04
【问题描述】:

我不会撒谎,正则表达式绝对不是我的强项,所以希望借用它的人的才能。

我需要做的是从一个看起来像这样的字符串;

location = "Somewhere" and (Person IN (4,1)) and status in ("Closed")

我特别需要这部分;

(Person IN (4,1))

其中(4,1)的部分可以包含一个一对多的数字数组。例如,如果我收到;

location = "Somewhere" and (Person IN (4,1,8,2,10,24,32,15,7)) and status in ("Closed")

那么我需要提取的部分是;

(Person IN (4,1,8,2,10,24,32,15,7)) 和包含的单词不区分大小写(例如;Person=person,IN=in)并且 number[] 中的数字之间可能有空格,但字符串和 number[] 都将是包含在(...) 中,如图所示,包含的字符串前后可能还有其他随机内容。

一个可怕的尝试可能是这样的:/(?:Person in \()(?:([\/\s"](?:,?)))(?:\))?/gm 但我知道这显然不是我需要的,请建议并帮助正则表达式业余爱好者哈哈。

【问题讨论】:

  • 你在哪里使用正则表达式?编程语言/工具?
  • @WiktorStribiżew 哦,对了,对不起。打字稿。
  • 你可以匹配括号和数字\(Person in \(\d+(?:,\d+)*\)\)regex101.com/r/FQzsSV/1
  • 是的,\(Person IN \(\d+(?:,\d+)*\)\) 也是我此时的建议。

标签: regex typescript


【解决方案1】:

您可以匹配左括号和右括号以及中间的逗号分隔数字,其中数字周围可以有可选的空白字符。

\(Person in \(\s*\d+\s*(?:,\s*\d+\s*)*\)\)
  • \(Person in \(匹配(Person in (
  • \s*\d+\s* 匹配可选空白字符之间的 1+ 个数字
  • (?:,\s*\d+\s*)* 可选地重复匹配可选空格字符之间的逗号和 1+ 位
  • \)\)匹配))

Regex demo

Javascript 示例

const regex = /\(Person in \(\s*\d+\s*(?:,\s*\d+\s*)*\)\)/gi;
const str = `location = "Somewhere" and (Person IN (4,1)) and status in ("Closed")

location = "Somewhere" and (Person IN ( 4, 1,8,2, 10,24 ,32,15, 7 )) and status in ("Closed")

location = "Somewhere" and (Person IN ()) and status in ("Closed")

location = "Somewhere" and (Person IN ( 4 )) and status in ("Closed")

`;
console.log(str.match(regex));

【讨论】:

  • 所以,如果我想用 .exec 输入像打字稿一样的东西,那就是 /\(Person in \(\s*\d+\s*(?:,\s*\d+\s*)*\)\)/gmi?
  • @ChrisW。您不需要 /m 标志。我添加了一个 JavaScript 示例。您需要 /g 来获取所有匹配项,并且需要 /i 来获取不区分大小写的匹配项。
【解决方案2】:

显然选择regex 是一个不错的选择。但也有一种方法可以使用substring 和indexOf 来实现。

var str = "location = \"Somewhere\" and (Person IN (4,1,8,2,10,24,32,15,7)) and status in (\"Closed\")"

let index1 = str.indexOf("(Person IN");
let index2 = str.substring(index1).indexOf(")");
console.log(str.substring(index1, index1+index2+2))

【讨论】:

  • 它错过了尾随的括号,但这很简单可以补救,好选择欢呼!
  • 是的,+2 而不是 +1 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
相关资源
最近更新 更多