Javascript 如何知道目标字符串之前是否有非空白字符?
我如何用正则表达式表示这一点,以知道在“#include”之前是否有非空白字符Javascript 如何知道目标字符串之前是否有非空白字符?,javascript,regex,Javascript,Regex,我如何用正则表达式表示这一点,以知道在“#include”之前是否有非空白字符 var-kword_search=“#includesomething”; /^?+\s*#include$/.test(kword_search)//必须返回false var kword_search=“asffs#includesomething”; /^?+\s*#include$/.test(kword_search)//必须返回true 在正则表达式中不是很好使用带适当量词的否定字符类。然后从末尾移除$
var-kword_search=“#includesomething”;
/^?+\s*#include$/.test(kword_search)//必须返回false
var kword_search=“asffs#includesomething”;
/^?+\s*#include$/.test(kword_search)//必须返回true
在正则表达式中不是很好使用带适当量词的否定字符类。然后从末尾移除
$
锚,字符串不会以include
结尾:
/^[^\s]+#include/.test(kword_search)
您可能正在寻找类似于
/^[\S]#include/
说明:
^ beginning of the string
[\S ] any character of: non-whitespace (all but
\n, \r, \t, \f, and " "), ' '
#include/ '#include/'
正则表达式快速参考
[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
简单地说:
\S#include
在jsfiddle@fireflieslive上查看一个通过测试的示例。您可以发布它不适用的字符串吗?这在
#include
之前同时包含空格和非空格字符的行上不起作用,这听起来像是OP想要的。尝试类似于^[^#]*[^\s#][^#]*.[^#]*.[include
的方法如果您接受了其中一个答案,请将其标记为已回答。@hnwd-抱歉,我忘了返回此线程,顺便问一下,为什么需要将其包含在[]中?它考虑使用字符类,例如多个正则表达式。在这种情况下,我怀疑你需要它,但我把它放在适当的地方。
/^(?:\s*|)#include/.test(kword_search)
/^(?:\s*|)#include/.test(kword_search)