使用Regex验证Useragent

时间:2018-08-17 21:16:58

标签: regex user-agent

我正在尝试验证具有以下格式的useragent

Mozilla/5.0 (Linux; U; Android <android>; <locale>; <device> Build/<build>) AppleWebKit/<webkit> (KHTML, like Gecko) Version/4.0 Mobile Safari/<safari>

用户代理可以是

Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; AFTB Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

到目前为止,我的正则表达式是

Mozilla\/5\.0 \(Linux; U; Android (\d+\.)?(\d+\.)?(\*|\d+); [a-z]{2}-[a-z]{2} (AFTA|AFTN|AFTS|AFTB|AFTT|AFTM|AFTKMST12|AFTRS) Build\/([A-Z0-9])\) AppleWebKit\/(\d+\.)?(\*|\d+) \(KHTML, like Gecko\) Version\/4\.0 Mobile Safari\/(\d+\.)?(\*|\d+)

测试:https://regex101.com/r/nXKYBB/1

但是不匹配。怎么了?

1 个答案:

答案 0 :(得分:1)

您错过了# Import 3rd party libraries from PyQt4 import QtGui, QtCore from PyQt4.QtCore import QObject, pyqtSignal import time import pyqtgraph # Import python standard modules import sys # This file holds the MainWindow import Plotter # Variables T = [0] R = [0] # Disregard this function def ReadChannel(channel): # some process return channel # ----------------------------------------------------------------- # ----------------------------------------------------------------- class Helper(QtCore.QObject): Sinal = QtCore.pyqtSignal(str, tuple) def Emt(self, arg1, arg2): self.Sinal.emit(arg1, arg2) class Ctrldr(QtGui.QMainWindow, Plotter.Ui_MainWindow): def __init__(self): super(self.__class__, self).__init__() self.setupUi(self) self.QOutput.clicked.connect(self.Calculo) self.helper = Helper(self) # <--- object # Plotting @QtCore.pyqtSlot(str, tuple) def Imprime(self, name, ptm): global T, R, W x, y = ptm R.append(y) self.graphicsView.plotItem.plot(T, R, pen='b') # Calculations def Calculo(self): global T t = time.clock() T.append(t) Read = ReadChannel(0) self.helper.Sinal.emit("Sensor", (t, Read)) Read = str(Read) self.QResult.setText(Read) # ----------------------------------------------------------------- if __name__ == '__main__': app = QtGui.QApplication(sys.argv) PID = Ctrldr() helper = Helper() helper.Sinal.connect(PID.Imprime) PID.show() app.exec_() 之后的;en-de之后的+

[A-Z0-9]

请参见regex demo

请注意,如果您不打算以后再使用那些捕获的子值,并使用Mozilla\/5\.0 \(Linux; U; Android (\d+\.)?(\d+\.)?(\*|\d+); [a-z]{2}-[a-z]{2}; (AFTA|AFTN|AFTS|AFTB|AFTT|AFTM|AFTKMST12|AFTRS) Build\/([A-Z0-9]+)\) AppleWebKit\/(\d+\.)?(\*|\d+) \(KHTML, like Gecko\) Version\/4\.0 Mobile Safari\/(\d+\.)?(\*|\d+) 来匹配空白,那么最好匹配非捕获组(?:...),而不是捕获组。

此外,如果您打算匹配整个字符串,请用\s^包裹模式。