如何匹配一个字符,除非它是具有正则表达式的特定字符串的一部分

时间:2014-03-20 09:14:21

标签: regex

不知道如何解释这个,所以一个例子:

xx_xx -> matches because of the underscore -> .*_.*

xx_t_xx -> dont want this to match as _t_ is an exception I want to ignore

xx_t_xx_xx -> matches as there is an underscore that is not part of the string _t_

xx_t_xx_t_xx -> no match

_t_ -> no match

_ -> match

_t__ -> match

匹配下划线,除非它是字符串_t_

的一部分

可以用正则表达式完成吗?

3 个答案:

答案 0 :(得分:2)

好的

使用此:^[a-z]+_[a-z]+$

这只会匹配一个下划线

即它匹配xx_xx但不匹配xx_t_xx

在你的控制台中试试这个:

var str = "xx_xx";
var res = /^[a-z]+_[a-z]+$/.test(str);
console.log(res);

还有一件事。 LEARN REGEX非常有帮助。你想从regexone开始

答案 1 :(得分:1)

最后完成,检查了所有条件。工作良好 试试这个,它接受任何单个字符。 这绝对适合你

^([^_]|(_t_))*_([^_]|(_t_))*$

答案 2 :(得分:1)

如果您的语言支持负面后瞻和负前瞻,则可以使用(?<!_t)_(?!t_)正则表达式。基本上,您搜索的_前面没有_t,后面没有t_