这肯定是某个地方......但是在浪费了相当多的时间之后,我找不到它:我想测试一个字符串匹配:"in"+ * +"ing".
换句话说,应该导致
" in terest ing "true,而
" in sist"和"str ing "应该失败.
我只对测试单个单词感兴趣,没有空格.
我知道我可以在两次测试中做到这一点,但我真的想做到这一点.一如既往,感谢您的帮助.
如果您特别想要匹配单词,请尝试以下方法:
/in[a-z]*ing/i
Run Code Online (Sandbox Code Playgroud)
如果你想要"in"后跟任何字符,然后是"ing",那么:
/in.*ing/i
Run Code Online (Sandbox Code Playgroud)
在i之后的第二/使它不区分大小写.如果你想在"in"和"ing"之间至少有一个字符*,+那么要么替换with ; *匹配零或更多.
给定字符串中的变量,您可以使用正则表达式来测试匹配,如下所示:
var str = "Interesting";
if (/in[a-z]*ing/i.test(str)) {
// we have a match
}
Run Code Online (Sandbox Code Playgroud)
UPDATE
"如果前缀和后缀存储在变量中会怎么样?"
然后,不要使用如上所示的正则表达式文字,而是使用new RegExp()并传递表示模式的字符串.
var prefix = "in",
suffix = "ing",
re = new RegExp(prefix + "[a-z]*" + suffix, "i");
if (re.match("Interesting")) {
// we have a match
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我所显示的所有正则表达式都将匹配更大字符串中任何位置的"in"内容.如果这个想法是测试整个字符串是否匹配Mattern的这样"有趣"将是一个比赛,但"noninterestingstuff"不会(根据stackunderflow的评论),那么你需要字符串的开始和结束相匹配^和$:
/^in[a-z]*ing$/i
Run Code Online (Sandbox Code Playgroud)
或者来自变量:
new RegExp("^" + p + "[a-z]*" + s + "$", "i")
Run Code Online (Sandbox Code Playgroud)
或者,如果您正在测试整个字符串,则不一定需要正则表达式(尽管我发现正则表达式更简单):
var str = "Interesting",
prefix = "in",
suffix = "ing";
str = str.toLowerCase(); // if case is not important
if (str.indexOf(prefix)===0 && str.endsWith(suffix)){
// match do something
}
Run Code Online (Sandbox Code Playgroud)
或者对于不支持.endsWith()的浏览器:
if (str.slice(0,prefix.length)===prefix && str.slice(-suffix.length)===suffix)
Run Code Online (Sandbox Code Playgroud)
"关于这个问题我能阅读的最好的是什么?"
MDN给出了JavaScript的正则表达式的概要.regular-expressions.info提供了一组更为通用的教程.
/in.+ing/ // a string that has `in` then at least one character, then `ing`
/in.+ing/.test('interesting'); // true
/in.+ing/.test('insist'); // false
/in.+ing/.test('string'); // false
/in.+ing/.test('ining'); // false, .+ means at least one character is required.
/in.*ing/.test('ining'); // true, .* means zero or more characters are allowed.
Run Code Online (Sandbox Code Playgroud)
如果您想将事物限制为一个单词,您可以使用\w单词字符速记。
/in\w+ing/.test('invents tiring') // false, space is not a "word" character.
/in.+ing/.test('invents tiring') // true, dot matches any character, even space
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3699 次 |
| 最近记录: |