使用正则表达式在我选择的前两个相同字符之间查找文本

时间:2019-07-18 16:04:54

标签: javascript regex codemirror

  

假设以下输出

20198818-119903 | firmware-check | passed: host test-1000 is connected to a test with Version: 333 | |
20198818-119903 | other-test-123 | passed: host test-1000 is connected to a test with 333:
20198818-119903 | test4| passed :| host | is connected to a test with 333
20198818-119903 | something | passed: host test-1000 is connected to a test with Version:
  
    

我想提取固件检查,other-test-123,test4之类的东西

  

因此基本上前两个竖线之间的所有内容。

我试图用txt2re解决此问题,但没有按我的意愿进行工作(例如,不忽略第三行的主机)。我从未使用过正则表达式,也不想仅针对这种特殊情况学习它。有人可以帮我吗?

3 个答案:

答案 0 :(得分:3)

您可以使用此

^[^|]+\|([^|]+)

enter image description here

let str = `20198818-119903 | firmware-check | passed: host test-1000 is connected to a test with Version: 333 | |
20198818-119903 | other-test-123 | passed: host test-1000 is connected to a test with 333:
20198818-119903 | test4| passed :| host | is connected to a test with 333
20198818-119903 | something | passed: host test-1000 is connected to a test with Version:`

let op = str.match(/^[^|]+\|([^|]+)/gm).map(m=> m.split('|')[1].trim())

console.log(op)

答案 1 :(得分:2)

此表达式将简单地提取这些值:

.*?\|\s*(.*?)\s*\|.*

DEMO

const regex = /.*?\|\s*(.*?)\s*\|.*/gm;
const str = `20198818-119903 | firmware-check | passed : host test-1000 is connected to a test with Version: 333 | |
20198818-119903 | other-test-123 | passed : host test-1000 is connected to a test with 333:
20198818-119903 | test4| passed :| host | is connected to a test with 333
20198818-119903 | something | passed : host test-1000 is connected to a test with Version:`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);

答案 2 :(得分:1)

您可以使用正则表达式/[^|]+\|\s*([^|]+)\s*\|.*/|之间的第一个匹配项添加到捕获组中。使用exec和while循环来获取所有匹配项。

(您也可以使用matchAll跳过while循环,但它仍处于草稿状态)

let str = `20198818-119903 | firmware-check | passed : host test-1000 is connected to a test with Version: 333 | |
20198818-119903 | other-test-123 | passed : host test-1000 is connected to a test with 333:
20198818-119903 | test4| passed :| host | is connected to a test with 333
20198818-119903 | something | passed : host test-1000 is connected to a test with Version:`,
    regex = /[^|]+\|\s*([^|]+?)\s*\|.*/g,
    match,
    matches = [];

while(match = regex.exec(str))
  matches.push(match[1])

console.log(matches)

// OR
// matchAll is still in Draft status
console.log(
  Array.from(str.matchAll(regex)).map(a => a[1])
)

Regex demo