简体   繁体   English

javascript 正则表达式匹配两个字符串并计算其中的字符数

[英]javascript regex match between two strings and count the number of characters inside

I'm very new to js and programming, and i'd appreciate some help.我对 js 和编程很陌生,我会很感激一些帮助。

Suppose I have the following array (It is a single element array, they are not seperate elements)假设我有以下数组(它是一个单元素数组,它们不是单独的元素)

var array =
[
     'Foo\n' +
      'bar23123\n' +
      'barbarfoo\n' +
      'foo, bar foo\n' +
      'foo\n' +
      '\n' +
      '\n' +
      'Bar\n' +
      '\n' +
      '\n'
  ]

Assuming there are multiple elements in the array, how can I write a regex expression to count and match the number of literal '\n' in between Foo\n and Bar\n in each element.假设数组中有多个元素,我如何编写一个正则表达式来计算和匹配每个元素中 Foo\n 和 Bar\n 之间的文字 '\n' 的数量。

I wrote a partial solution to iterate through and return the count of all \n but how do I narrow my search to only return the values in between the two strings?我编写了一个部分解决方案来迭代并返回所有 \n 的计数,但是如何缩小搜索范围以仅返回两个字符串之间的值?

Here is the code:这是代码:

let slashN = [];
for(let slash of array){
   var reg = RegExp('\\n' , 'g')
  slashN.push(slash.match(reg).length)
}

console.log(slashN);

I get the correct count, but I want to refine the regex expression.我得到了正确的计数,但我想改进正则表达式。

Any help is highly appreciated.非常感谢任何帮助。

You may use您可以使用

var reg = /(?<=Foo\n.*?)\n(?=.*?Bar\n)/gs;

See the regex demo .请参阅正则表达式演示 Details :详情

  • (?<=Foo\n.*?) - a positive lookbehind that matches a location that is immediately preceded with Foo + newline and then any 0 or more chars, as few as possible (?<=Foo\n.*?) - 一个正向的向后查找,它匹配紧接在Foo + 换行符之前的位置,然后是任何 0 个或多个字符,尽可能少
  • \n - a newline \n - 换行符
  • (?=.*?Bar\n) - a positive lookahead that matches a location immediately followed with any 0+ chars as few as possible and then Bar + newline. (?=.*?Bar\n) - 一个正向前瞻,它与紧随其后的任何 0+ 字符尽可能少的位置匹配,然后是Bar + 换行符。

JavaScript demo: JavaScript 演示:

 var array = [ 'Foo\n' + 'bar23123\n' + 'barbarfoo\n' + 'foo, bar foo\n' + 'foo\n' + '\n' + '\n' + 'Bar\n' + '\n' + '\n' ]; let slashN = []; for(let slash of array){ var reg = /(?<=Foo\n.*?)\n(?=.*?Bar\n)/gs; slashN.push(slash.match(reg).length) } console.log(slashN);

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

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