计算以特定单词开头的行中的单词数

Count the number of words in the line beginning with a particular word

本文关键字:单词数 开头 单词 计算      更新时间:2023-09-26

我想计算包含特定ID(例如*AUY)的特定行中的单词数。到目前为止,我已经尝试使用下面的正则表达式来查找行,但它不考虑"*"在开始

^ *(.*'b(?:''*AUY)'b.*) *$

下面是test string

*AUY:   today is holiday so Peter and Mary do not need to go to work .
%mor:   n|today cop|be&3s n|holiday conj|so n:prop|Peter conj|and n:prop|Mary v|do neg|not v|need inf|to v|go prep|to n|work .
%snd:   <00:00:00><00:07:37>
%AUY:   ok_pfp (0.40) er today is holiday errfr ::: so er Peter and Mary {is} ~ er do not need errfr ::: to go to work . errfr :;:a |

结果应该只是第一个字符串,但它返回结果匹配中的第一个和最后一个字符串。

x为字符串。

(x.match(/(^|'n)'*AUY[^'r'n]*/g) || [])
    .map(
        function(s) { return s.match(/'S+/g).length; }
    );

将返回一个数组,其中包含以字符串'*AUY'开头的行中类字结构的个数。

解释:

正则表达式在字符串的开头或换行符之后查找字符串*AUY(即,在行开头,即使该行不是字符串的开头),以及在*AUY的第一个标记之后的任何非crlf字符(即,该行的其余部分)。

习惯用法|| []在执行匹配后,如果匹配值为null,则返回一个空数组,从而防止当期望一个数组而不是空值时出现错误。

最后一步.map对匹配数组的每个元素进行操作,对非空格匹配进行计数,并将这些计数作为一个新数组返回。注意,我们不需要用|| []习语保护这个匹配,因为空匹配是不可能的,因为该行至少包含非空白字符串*AUY。

您可以使用这段代码作为您实际想要做的事情的起点。好运!

试试:

/^.*?'*AUY:(.*?)$/gmi

解释
  1. ^确定行起始位置
  2. . * ?匹配任何字符(行终止符除外)
  3. * ?量词- 0到无限次之间的匹配(惰性)
  4. '*匹配字符*
  5. AUY:匹配字符AUY
  6. . * ?匹配任何字符(行终止符除外)
  7. $在行末断言位置
  8. g修饰符:global。第一次匹配后不返回
  9. m修饰符:多行。导致^和$匹配的开始/结束每一行(不只是字符串的开始/结束)
  10. i修饰符:insensitive

Rubular

代码示例:

function countWord(){
const regex = /^.*?'*AUY:(.*?)$/gmi;
const str = `*AUY:  today is holiday so Peter and Mary do not need to go to work .
%mor:   n|today cop|be&3s n|holiday conj|so n:prop|Peter conj|and n:prop|Mary v|do neg|not v|need inf|to v|go prep|to n|work .
%snd:   <00:00:00><00:07:37>
%AUY:   ok_pfp (0.40) er today is holiday errfr ::: so er Peter and Mary {is} ~ er do not need errfr ::: to go to work . errfr :;:a |`;
let m;
while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    alert(m[1].match(/'b('w+)'b/g).length);
}
    }

使用以下正则表达式,

(^.*'*AUY.*$)

可以在这里勾选