简体   繁体   中英

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.

https://regex101.com/r/x4EA4g/3

Try this one (?:\\s|^)\\S{0,10}test

https://regex101.com/r/M2oLJe/1

The following regex would match strings with 10 or fewer non-whitespace characters in front of test , ignoring whitespace characters:

(?:^\s*(?:\S\s*){0,10})test.*

Demo: https://regex101.com/r/x4EA4g/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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