簡體   English   中英

正則表達式,我怎么說,除了一個字,其他都匹配?

[英]Regex, how do I say, match everything but one word?

我正在使用正則表達式嘗試匹配任何一個單詞,但該單詞為'/ item /'。

([^/]+)

可以匹配任何東西(真),但是如果其中有“ / item /”這個詞,我希望它是假的。

我需要做這樣的事情嗎?

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

管道是“或”的地方! 是“不是”,我寫的這個示例絕對是錯誤的語法...關於正則表達式,我是個新手。

更新:

這是現場示例:

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

類別/全天候柳條/百慕大/ / 2977 / 應該通過

類別/全天候柳條/百慕大/ 項目 / 2977 / 應該會失敗

謝謝你的幫助!

如果您的字符串始終是一致的,則可以在此處使用負向超前

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

觀看現場演示

嘗試這個:

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");
}

現場演示

說明:

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) «$»

嗨,您可以嘗試反向邏輯,可能更容易查找'/ 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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM