带有排除字符和另一个正则表达式的正则表达式 [英] Regex with exclusion chars and another regex
问题描述
如何编写正则表达式来查找不包含某些字符(如 *
或 #
)的单词(不含空格)和句子(如 level10
或 level2
- 它也应该是正则表达式 - level[0-9]+
).排除字符 ([^\\s^#^*]+
) 会很简单,但是如何排除这个 'level'
示例呢?
How to write regex which find word (without whitespace) that doesn't contain some chars (like *
or #
) and sentence also (like level10
or level2
- it should be also regex - level[0-9]+
). It will be simple for chars excluded ([^\\s^#^*]+
) but how to exclude this 'level'
example too ?
我想用数字排除字符和级别.
I want to exclude chars AND level with number.
- 示例:
- weesdlevel3fv - 由于 'level3' 不应该匹配
- we3rlevelw4erw - 应该匹配 - 有没有数字的级别
- dfs3leveldfvws#3vd - 不应该匹配 - 级别很好,但出现了#"字符
- level4#level levelw4_level - 由于空格而威胁为两个词 - 只有第二个应该匹配 - 没有带数字的级别,也没有像#"或*"这样的限制字符
推荐答案
看到这个正则表达式:
/(?<=\s)(?!\S*[#*])(?!\S*level[0-9])\S+/
正则表达式解释:
(?<=\s)
在空白序列之后断言位置.(?!\S*[#*])
断言 #" 或 *" 不存在在序列中.(?!\S*level[0-9])
断言level[0-9]
在顺序.\S+
现在我们的条件通过了,这个序列是有效的.继续使用\S+
或\S++
来匹配整个序列.
(?<=\s)
Asserts position after a whitespace sequence.(?!\S*[#*])
Asserts that "#" or "*" is absent in the sequence.(?!\S*level[0-9])
Asserts thatlevel[0-9]
is not matched in the sequence.\S+
Now that our conditionals pass, this sequence is valid. Go ahead and use\S+
or\S++
to match the entire sequence.
要更专门地使用前瞻,您可以添加另一个 (?!\S*
组.
To use lookaheads more exclusively, you can add another (?!\S*<false_to_assert>)
group.
对于这种特定情况,您可以使用双重否定技巧:
For this specific case you can use a double negation trick:
/(?<=\s)(?!\S*level[0-9])[^\s#*]+(?=\s)/
阅读更多:
这篇关于带有排除字符和另一个正则表达式的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!