简体   繁体   English

用正则表达式提取单词,除非它是给定单词

[英]Extract word with regex except if it is a given word

I am trying to match and extract part of an URL with regex, except if it is a given word. 我试图用正则表达式匹配并提取URL的一部分,除非它是给定的单词。

Here is some test data which already works: 这是一些已经有效的测试数据:

/api/add             --> no match
/api/add/view        --> no match
/api/user1           --> matches and extracts "user1"
/api/user1/profile/  --> matches and extracts "user1"

Not working: 无法运作:

/api/aaa/profile/  --> matches and extracts "aaa"

Here is the current regex I have: 这是我当前的正则表达式:

/^\/api\/(?:([^\/(add)]+?))\/.*?$/i

I works as I want except if it contains "a" or "d" instead of the entire "add" word. 我可以按自己的意愿工作,除非它包含“ a”或“ d”而不是整个“ add”一词。

You may use this regex: 您可以使用此正则表达式:

/^\/api\/(?!add(?:\/|$))([^\/]+)/i

RegEx Demo 正则演示

In your regex when you use [^\\/(add)]+ that means any character except any of / . 在正则表达式中,当您使用[^\\/(add)]+ ,表示除/以外的任何字符。 ( , a , d , ) characters because inside character class ie [...] there is no grouping. (ad)字符,因为在字符类即即[...]中没有分组。

如果您希望匹配“ / api / * / whatever”并返回为*找到的内容,除非它是“ add”

/^\/api\/(?!add\b)(\w+)(?:\/\w+)*\/?$/i 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM