用于查找不以“my:”开头的单词的 Javascript 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17756441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript regex to find words that do not start with "my:"
提问by Anthony
I'm trying to write a regex that will find all values between curly braces that do not begin with "my:". For example, I want to capture {this}
but not {my:monkey}
.
我正在尝试编写一个正则表达式,它将找到不以“my:”开头的大括号之间的所有值。例如,我想捕获{this}
但不是{my:monkey}
.
The pattern that captures everything is:
捕捉一切的模式是:
\{([^\}]*)\}
I'm having trouble getting it to work. My closest shot so far is:
我很难让它工作。到目前为止,我最近的镜头是:
\{[^my:]*([^\}]*)\}
This fails because it only ignores tags beginning with "m", "y" or ":".
这会失败,因为它只忽略以“m”、“y”或“:”开头的标签。
I'm sure there is a command I'm overlooking to treat "my:" as a block..
我确定有一个命令我忽略了将“我的:”视为一个块..
(Note: Must work for Javascript)
(注意:必须适用于 Javascript)
回答by elclanrs
回答by p.s.w.g
You can do something like this:
你可以这样做:
var input = "I want to capture {this} but not {my:monkey}";
var output = input.replace(/{(my:)?([^}]*)}/g, function(// test match thing_done but not some_thing_done (using nagative lookbehind)
console.log(/(?<!some_)thing_done/.test("thing_done")); // true
console.log(/(?<!some_)thing_done/.test("some_thing_done")); // false
// test match thing_done but not think_done_now (using nagative lookahead)
console.log(/thing_done(?!_now)/.test("thing_done")); // true
console.log(/thing_done(?!_now)/.test("thing_done_now")); // false
// test match some_thing_done but not some_thing (using positive lookbehind)
console.log(/(?<=some_)thing_done/.test("thing_done")); // false
console.log(/(?<=some_)thing_done/.test("some_thing_done")); // true
// test match thing_done but not think_done_now (using positive lookahead)
console.log(/thing_done(?=_now)/.test("thing_done")); // false
console.log(/thing_done(?=_now)/.test("thing_done_now")); // true
, , ) {
return ? I need match some_thing_done not thing_done:
Put `some_` in brace: (some_)thing_done
Then put ask mark at start: (?some_)thing_done
Then need to match before so add (<): (?<some_)thing_done
Then need to equal so add (<): (?<=some_)thing_done
--> (?<=some_)thing_done
?<=some_: conditional back equal `some_` string
: "[MATCH]";
});
// I want to capture [MATCH] but not {my:monkey}
回答by Steve Allison
{(?!my:)(.*?)}
works in regex pal: http://preview.tinyurl.com/nkcpoy7
{(?!my:)(.*?)}
在正则表达式中工作:http: //preview.tinyurl.com/nkcpoy7
回答by o0omycomputero0o
Summarize as following:
总结如下:
##代码##Dialogue version:
对话版:
##代码##Link example code: https://jsbin.com/yohedoqaxu/edit?js,console