简体   繁体   中英

How to know if there are non-whitespace char before the target string?

How do i express this in regex to know if there are non-whitespace chars before '#include'?

var kword_search = "#include<iostream.>something";
/^?+\s*#include$/.test(kword_search)//must return false

var kword_search = "asffs#include<iostream.>something";
/^?+\s*#include$/.test(kword_search)//must return true

Not really good in regex

You are likely looking for something like /^[\\S ]#include/

Explanation:

 ^                         beginning of the string
  [\S ]                    any character of: non-whitespace (all but
                           \n, \r, \t, \f, and " "), ' '
   #include/               '#include/'

Regex quick reference

[abc]      A single character: a, b or c
[^abc]     Any single character but a, b, or c
[a-z]      Any single character in the range a-z
[a-zA-Z]   Any single character in the range a-z or A-Z
^          Start of line
$          End of line
\A         Start of string
\z         End of string
.          Any single character
\s         Any whitespace character
\S         Any non-whitespace character
\d         Any digit
\D         Any non-digit
\w         Any word character (letter, number, underscore)
\W         Any non-word character
\b         Any word boundary character
(...)      Capture everything enclosed
(a|b)      a or b
?          Zero or one
*          Zero or more
+          One or more

Use negated character class, with appropriate quantifier. And remove the $ anchor from the end, your string doesn't end with include :

/^[^\s]+#include/.test(kword_search)

Simply:

\S#include

See a live demo passing your tests on jsfiddle

/^(?:\s*|)#include/.test(kword_search)

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