简体   繁体   English

正则表达式计算文本缩进中空格和制表符的数量

[英]Regex counting number of space and tab in text indent

I'm trying to find a RegEx solution that let me count the number of tab-press and space-key-press against a text indent.我正在尝试找到一个 RegEx 解决方案,让我可以根据文本缩进计算 Tab-press 和 space-key-press 的数量。 It should support counting following scenarios:它应该支持计数以下场景:

\\t\\tWelcome to Hello World (2 tab press) \\t\\t欢迎来到 Hello World (2 tab press)

\\s\\s\\s\\s\\tWelcome to Hello World (4 space and one tab) \\s\\s\\s\\s\\t欢迎来到 Hello World (4 space and one tab)

\\s\\s\\t\\s\\s\\tWelcome to Hello World (combinations of repeated space and tabs) \\s\\s\\t\\s\\s\\tWelcome to Hello World (combinations of repeated space and tabs)

\\t\\s\\sWelcome to Hello World (one tab 2 spaces) \\t\\s\\sWelcome to Hello World (one tab 2 spaces)

If you wanted to use JavaScript regex for this, one way to count the number of occurrences would be to compare the length of the string before and after replacements of the various whitespace characters, eg如果您想为此使用 JavaScript 正则表达式,计算出现次数的一种方法是比较替换各种空白字符之前和之后的字符串长度,例如

 var input = " \\tWelcome to Hello World"; input = input.replace(/^(\\s+).*$/, "$1"); var num_spaces = input.length - input.replace(/[ ]/g, "").length; var num_tabs = input.length - input.replace(/\\t/g, "").length; console.log("There are " + num_spaces + " spaces."); console.log("There are " + num_tabs + " tabs.");

The second line in the above code snippet strips off all text appearing after the initial cluster of whitespace characters.上面代码片段中的第二行去除了出现在初始空白字符簇之后的所有文本。

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

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