是否存在正则表达式来匹配包含A但不包含B的字符串 [英] Is there a regex to match a string that contains A but does not contain B

查看:352
本文介绍了是否存在正则表达式来匹配包含A但不包含B的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是我想使用纯正则表达式检查浏览器字符串。

My problem is that i want to check the browserstring with pure regex.

Mozilla/5.0 (Linux; U; Android 3.0; en-us; Xoom Build/HRI39) AppleWebKit/534.13 (KHTML, like Gecko) Version/4.0 Safari/534.13

->应该匹配

Mozilla/5.0 (Linux; U; Android 2.2.1; en-us; Nexus One Build/FRG83) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 

不匹配

我尝试过的解决方案是: /?((?< = Android)(?:[^])*?( ?= Mobile))/ i
,但匹配完全错误。

my tried solution is: /?((?<=Android)(?:[^])*?(?=Mobile))/i but it matches exactly wrong.

推荐答案

您使用前瞻性断言来检查字符串中是否包含单词。

You use look ahead assertions to check if a string contains a word or not.

如果您要确保字符串在某个位置包含 Android,则可以这样做

If you want to assure that the string contains "Android" at some place you can do it like this:

^(?=.*Android).*

您也可以将它们合并,以确保其中包含 Android某个地方,然后在某个地方移动:

You can also combine them, to ensure that it contains "Android" at some place AND "Mobile" at some place:

^(?=.*Android)(?=.*Mobile).*

如果要确保某个单词不在字符串中,请使用负号:

If you want to ensure that a certain word is NOT in the string, use the negative look ahead:

^(?=.*Android)(?!.*Mobile).*

这将要求单词 Android包含在字符串中,而单词 Mobile不允许包含在字符串中。 。* 部分匹配,当开头的断言为真时,则匹配完整的字符串/行。

This would require the word "Android to be in the string and the word "Mobile" is not allowed in the string. The .* part matches then the complete string/row when the assertions at the beginning are true.

查看它在Regexr上

这篇关于是否存在正则表达式来匹配包含A但不包含B的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆