在RegExp lookbehind断言中转义字符

时间:2017-10-18 03:24:15

标签: javascript regex

Regex to match url segment only if not preceded by specific parent segment

给出输入

http://example.com/my-slughttp://example.com/my-slug/

要求是匹配

"my-slug"

但不匹配

"my-slug"

如果前面有

"news-events"

能够使用"/my-slug""/my-slug/"在Chromium使用--harmony标记设置为RegExp

时匹配// why is the `\/` necessary following lookbehind? let re = /(?<!news-events)\/[^/]+(?=\/$|$)/; let sources = [ "http://example.com/my-slug" , "http://example.com/my-slug/" , "http://example.com/news-events/my-slug" ]; for (let src of sources) { console.log(src.match(re)) }"my-slug"

&#13;
&#13;
"/"
&#13;
&#13;
&#13;

但是,当尝试通过"/"转发news-event/ RegExp时,"http://example.com/news-events/my-slug"之前没有"y-slug"字符来精确匹配nulllet re = /(?<!news-events\/)[^/]+(?=\/$|$)/; let sources = [ "http://example.com/my-slug" , "http://example.com/my-slug/" , "http://example.com/news-events/my-slug" ]; for (let src of sources) { console.log(src.match(re)) }不会返回同一匹配,当预期结果为"/"

时,RegExp的匹配为RegExp

&#13;
&#13;
"news-events/"
&#13;
&#13;
&#13;

问题:

  • 为什么转义的"my-slug"字符不包含在\/外观否定断言的一部分中?

  • 如何正确转义字符或以其他方式调整error.js:170 Experiment amp-ima-video is disabled. Wd @ error.js:170 (anonymous) @ error.js:108 f.assert @ log.js:325 log.js:319 Uncaught (in promise) Error: failed to build: amp-ima-video#1: Experiment amp-ima-video is disabled. lookbehind断言以取消完整字符串Traceback (most recent call last): File "C:\Program Files\Python35\lib\threading.py", line 914, in _bootstrap_inner self.run() File "C:\Program Files\Python35\lib\threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "C:\Users\jerem\Source\Repos\ets-ws\python\shot_caller.py", line 73, in add_log add_log(cursor, current_log) TypeError: add_log() takes 1 positional argument but 2 were given 并返回预期结果cursor = dev_db_connection() log_queue = queue.Queue() def add_log(cursor): while True: if log_queue.empty() == False: current_log = log_queue.get() add_log(cursor, current_log) 而无需包含def add_log(cursor, current_log): return sql_query(cursor, """SQL query string""") 在应该匹配的字符串部分之前?

1 个答案:

答案 0 :(得分:1)

从正则表达式的这一位开始:

[^/]+(?=\/$|$)

匹配文本y-slugy-slug是多个非斜杠字符,可选后跟斜杠,后跟字符串的结尾),而y-slug前面没有{ {1}},这是一个有效的匹配。由于news-events/不匹配,因此它也是第一个有效匹配,因此它是返回的匹配。

您可以添加第二个正面的lookbehind来指示任何匹配必须是完整的分段。

my-slug