正则表达式,我怎么说,只匹配一个字?

时间:2014-05-06 16:29:39

标签: javascript regex iis

使用正则表达式我试图匹配任何一个单词,该单词为'/ item /'。

([^/]+)

匹配任何内容(true),但如果单词'/ item /'在那里,我希望它是假的。

我必须做这样的事吗?

([^/]+|!/item/)

管道是'或'的地方!是'不是',我写的这个例子绝对是错误的语法......当谈到正则表达式时,我是个新手。

更新

以下是实例:

^(category)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$

类别/全天候柳条/百慕大/ / 2977 / 应该通过

类别/全天候柳条/百慕大/ 项目 / 2977 / 应该失败

感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

如果您的字符串始终保持一致,则可以在此处使用否定前瞻

^(category)/([^/]+)/([^/]+)/((?:(?!\bitem\b).)+)/([^/]+)/?$

请参阅live demo

答案 1 :(得分:0)

试试这个:

var subject = "category/all-weather-wicker/bermuda/item/bermuda-end-table/table/2977/";
if (/^category(?!.*?\/item\/\d+\/).*?$/im.test(subject)) {
    console.log("passed");
} else {
    console.log("failed");
}

<强> LIVE DEMO

<强> 说明:

Assert position at the beginning of a line (at beginning of the string or after a line break character) (line feed, line feed, line separator, paragraph separator) «^»
Match the character string “category” literally (case insensitive) «category»
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*?/item/\d+/)»
   Match any single character that is NOT a line break character (line feed, carriage return, line separator, paragraph separator) «.*?»
      Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
   Match the character string “/item/” literally (case insensitive) «/item/»
   Match a single character that is a “digit” (ASCII 0–9 only) «\d+»
      Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   Match the character “/” literally «/»
Match any single character that is NOT a line break character (line feed, carriage return, line separator, paragraph separator) «.*?»
   Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»
Assert position at the end of a line (at the end of the string or before a line break character) (line feed, line feed, line separator, paragraph separator) «$»

答案 2 :(得分:0)

嗨,你可以试试反向逻辑,可能更容易找到'/ item /'的存在

...的JavaScript

var st1 = 'here is a string with /item/ in it';
var m = st1.match(/\/\bitem\b\//g);
m = (m !== null)?false:true;
console.log(m);

注意:不要忘记逃避“/”,如“\ /”

这是一个小提琴演示...

http://jsfiddle.net/KF4De/