简体   繁体   English

如何使用正则表达式匹配特定字符后的整个单词或句子

[英]How to match a whole word or sentence after a specific character with regexp

I have an object that contains other objects, some of these have a key that is a string that starts with column like this: ':Campaign':{data} I need to loop through that object and save all the keys that start with column (:) into strings.我有一个包含其他对象的 object,其中一些对象有一个键,该键是以这样的列开头的字符串: ':Campaign':{data} 我需要遍历 object 并保存所有以列开头的键(:) 成字符串。 For that I need a regex that matches the first character: and take the whole word right after:为此,我需要一个与第一个字符匹配的正则表达式:并在之后立即获取整个单词:

so far I wrote this but found returns only the column:到目前为止我写了这个但发现只返回列:

const keys = Object.keys(output)
const regex = /^:*/gi;

keys.forEach(key =>  {
  const found = key.match(regex);
  console.log('found: ', found);
})

Log is:日志是:

found:  [ ':' ]
found:  [ ':' ]

Here are 2 options depending on whether you want to include the colon in the pattern that you are capturing.这里有 2 个选项,具体取决于您是否要在捕获的模式中包含冒号。

  • with the colon ^:\w*用冒号^:\w*
  • with a lookback for the colon (?<=^:)\w*回顾一下冒号(?<=^:)\w*
    This will match a word after the colon.这将匹配冒号后的单词。
    You may want any number of any character .* or any combination of word characters and spaces `[\w\s]*您可能需要任意数量的任意字符.*或单词字符和空格的任意组合 `[\w\s]*

Try this !尝试这个 !

[':].*['] [':].*[']

It should give you the whole key in single quotes.它应该为您提供单引号中的整个密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM