javascript正则表达式计算空白字符 [英] javascript regex to count whitespace characters

查看:72
本文介绍了javascript正则表达式计算空白字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用javascript正则表达式来计算字符串中第一个文本字符之前的空白字符数吗?我只关心是否有0,1和2 +。

Can I use a javascript regex to count the number of whitespace characters before the first text character in the string? I only care if there are 0, 1, and 2+.

我目前正在使用的解决方案是使用三个正则表达式并使用匹配来确定0,1,或者2+类别(每个都有单独的模式),但我正在寻找更优雅的解决方案。

My current working solution is to have three regexes and just use match to determine the 0,1, or 2+ category(separate pattern for each), but Im looking for a more elegant solution.

甚至可以用正则表达式计算模式吗?我可以使用非贪婪的分组并计算我猜的长度....

Is it even possible to count patterns with regex? I could use a non-greedy grouping and count the length I guess....

推荐答案

"     a".match(/^\s{0,2}/)[0].length

此正则表达式匹配字符串开头的0到2个空格字符。

This regex matches between 0 and 2 whitespace characters at the beginning of a string.

这篇关于javascript正则表达式计算空白字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆