正则表达式:在文本中查找带标签的字符串

问题描述 投票:1回答:2

我得到了以下查询字符串,该字符串始终在字符串的末尾包含几个标记值(key: value对):

Lorem ipsum age:85 date:15.05.2015 sender: user: John Doe

“ Lorem ipsum”是一个字符串,因为它不是一对,所以应该忽略。以下对有效:

  • [age85
  • [date15.05.2015
  • [userJohn Doe

如果在冒号后找不到内容,则应忽略标签。它们的内容还可以包含空格,直到下一个标记的键为止。

这是我到目前为止所得到的:

/([\w-]+):\s*(.+?)(?!\s+[\w-]+:)?/g

但是由于某种原因,它似乎仅与值的第一个字符匹配,并且还切入了“用户”标签(regexr playground):

age:8
date:1
sender: u
ser:J

任何帮助将不胜感激!

regex regex-lookarounds
2个回答
2
投票

您可以使用

(\w[\w-]*):(?!\s+\w[\w-]*:|\s*$)\s*(.*?)(?=\s+\w[\w-]*:|$)

请参见regex demo

详细信息

  • [(\w[\w-]*)-捕获组1:一个单词字符,后跟0+个单词或连字符]
  • [:-冒号
  • [(?!\s+\w[\w-]*:|\s*$)-如果在当前位置的右边,如果有1+个空格,一个单词char后面跟着0+ word或连字符,然后是:或0+空白,字符串的结尾
  • \s*-0+空格
  • (.*?)-组2:除换行符以外的任何零个或多个字符,应尽可能少,直到最接近的...
  • [(?=\s+\w[\w-]*:|$)-1+个空格,一个单词char后跟0+个单词或连字符,然后是:或只是字符串的结尾。

1
投票

我似乎从以下模式获得了不错的成绩:

(?<!\S)\S+:\s*\S*[^:\s](?!\S)

Demo

这里的策略是先匹配一个键,再匹配一个冒号,然后再匹配可选的空格,并且一个<< not>也不要以冒号结尾的术语(以防止溢出到另一个键)。这是正则表达式的解释:(?<!\S) assert that what precedes the start of the key is either whitespace or the start of the string \S+ match one or more non whitespace characters (the key) : followed by : \s* followed by optional whitespace \S* a value, zero or more non whitespace characters [^:\s] ending in a non colon (?!\S) assert that what follows is either whitespace or the end of the string

© www.soinside.com 2019 - 2024. All rights reserved.