正则表达式:在文本中查找标记的字符串
Regex: Find tagged strings in text
我得到以下查询字符串,其中包含一对始终位于字符串末尾的标记值(key: value
对):
Lorem ipsum age:85 date:15.05.2015 sender: user: John Doe
"Lorem ipsum" 是一个应忽略的字符串,因为它不是一对。
以下对有效:
age
与 85
date
与 15.05.2015
user
与 John Doe
如果在冒号后找不到内容,则应忽略标记。
它们的内容还可以包含直到下一个标签键的空格。
这是我目前得到的结果:
/([\w-]+):\s*(.+?)(?!\s+[\w-]+:)?/g
但由于某种原因它似乎只匹配值的第一个字符并且还切入了"user"标签(regexr playground):
age:8
date:1
sender: u
ser:J
如有任何帮助,我们将不胜感激!
您可以使用
(\w[\w-]*):(?!\s+\w[\w-]*:|\s*$)\s*(.*?)(?=\s+\w[\w-]*:|$)
详情
(\w[\w-]*)
- 捕获第 1 组:一个单词字符后跟 0+ 个单词或连字符字符
:
- 冒号
(?!\s+\w[\w-]*:|\s*$)
- 如果在当前位置的右侧立即有 1+ 个空格,一个单词 char 后跟 0+ 个单词或连字符,然后 :
或字符串末尾的 0+ 个空格
\s*
- 0+ 个空格
(.*?)
- 第 2 组:除换行符以外的任何零个或多个字符,尽可能少,最接近...
(?=\s+\w[\w-]*:|$)
- 1+ 个空格,一个单词字符后跟 0+ 个单词或连字符字符,然后是 :
或只是字符串的末尾。
我似乎从以下模式中获得了不错的成绩:
(?<!\S)\S+:\s*\S*[^:\s](?!\S)
这里的策略是匹配一个键后跟冒号,然后是可选的空格和一个 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
我得到以下查询字符串,其中包含一对始终位于字符串末尾的标记值(key: value
对):
Lorem ipsum age:85 date:15.05.2015 sender: user: John Doe
"Lorem ipsum" 是一个应忽略的字符串,因为它不是一对。 以下对有效:
age
与85
date
与15.05.2015
user
与John Doe
如果在冒号后找不到内容,则应忽略标记。 它们的内容还可以包含直到下一个标签键的空格。
这是我目前得到的结果:
/([\w-]+):\s*(.+?)(?!\s+[\w-]+:)?/g
但由于某种原因它似乎只匹配值的第一个字符并且还切入了"user"标签(regexr playground):
age:8
date:1
sender: u
ser:J
如有任何帮助,我们将不胜感激!
您可以使用
(\w[\w-]*):(?!\s+\w[\w-]*:|\s*$)\s*(.*?)(?=\s+\w[\w-]*:|$)
详情
(\w[\w-]*)
- 捕获第 1 组:一个单词字符后跟 0+ 个单词或连字符字符:
- 冒号(?!\s+\w[\w-]*:|\s*$)
- 如果在当前位置的右侧立即有 1+ 个空格,一个单词 char 后跟 0+ 个单词或连字符,然后:
或字符串末尾的 0+ 个空格\s*
- 0+ 个空格(.*?)
- 第 2 组:除换行符以外的任何零个或多个字符,尽可能少,最接近...(?=\s+\w[\w-]*:|$)
- 1+ 个空格,一个单词字符后跟 0+ 个单词或连字符字符,然后是:
或只是字符串的末尾。
我似乎从以下模式中获得了不错的成绩:
(?<!\S)\S+:\s*\S*[^:\s](?!\S)
这里的策略是匹配一个键后跟冒号,然后是可选的空格和一个 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