Is there a regex to match a string that contains A but does not contain B

后端 未结 3 495
眼角桃花
眼角桃花 2020-12-07 20:35

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,         


        
3条回答
  •  不知归路
    2020-12-07 21:18

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

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

    ^(?=.*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).*
    

    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.

    See it here on Regexr

提交回复
热议问题