0

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. It should support counting following scenarios:

\t\tWelcome to Hello World (2 tab press)

\s\s\s\s\tWelcome to Hello World (4 space and one tab)

\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)

Santanu Karar
  • 854
  • 8
  • 23

1 Answers1

1

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, e.g.

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.

Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263