javascript - Match string with 10 or fewer non-whitespace characters in front of string, ignoring whitespace characters
问题描述
I'm trying to write a regular expression that will search for the word test
and match with the following strings:
test
test
//test
// tests
// test
// 1 2 34 test
But it would fail against the following:
// 1234567890 test
12345678901test
So far I have (?=\S|\s)test([^\n]*)
, which weems to work, aside from the 0-10 non-whitespace characters. Here's a regex101 link.
解决方案
You can use:
/^(?=(\s*?\S?){0,10}test).*?test/
It uses a positive lookahead to assert the use-case so that the capture doesn't bleed onto other lines.