Python正则表达式:为什么可选匹配总是返回null?

时间:2019-04-30 04:37:15

标签: python regex

我想在文本中了解协议。如果我这样做是:

>>> d = re.search(re.compile(r".*(?P<protocol>(http\/\d\.\d)?) (?P<statuscode>\d{3})"), 'khkhjkhkhkh HTTP/1.1 303')
>>> d.groupdict()["protocol"]

结果将为空,因为如果我删除'?',则将协议与。*匹配对于该协议,它在这种情况下可以正常工作,但对于缺少该协议的情况(例如“ khkhjkhkhkh 303”)不起作用。我知道让regex匹配协议而不是。*令人困惑,但是可以解决此问题吗?

1 个答案:

答案 0 :(得分:2)

由于协议模式是可选的,因此第一个new Date(dob)将尽可能匹配(贪婪)直至强制状态码模式。根据评论,您需要非贪婪的变体:var minDate = new Date('04/30/1937'); var maxDate = new Date('04/30/2004'); var dob = new Date('09/14/1993'); //new date(dob). I used a hardcoded date if (dob < minDate) { result = false; console.log("You are too old to be applying for this position") } else if(dob > maxDate ) { result = false; console.log("You are too young to be applying for this position") } else { result = true; console.log("success") }

您还需要匹配不区分大小写的字符串,因为您的模式具有version: '3.3' services: db: image: mysql:5.7 volumes: - db_data:/var/lib/mysql restart: always environment: MYSQL_ROOT_PASSWORD: somewordpress MYSQL_DATABASE: wordpress MYSQL_USER: wordpress MYSQL_PASSWORD: wordpress wordpress: depends_on: - db image: wordpress:latest ports: - "8000:80" restart: always environment: WORDPRESS_DB_HOST: db:3306 WORDPRESS_DB_USER: wordpress WORDPRESS_DB_PASSWORD: wordpress WORDPRESS_DB_NAME: wordpress volumes: db_data: {} ,但是搜索字符串具有.*

一起:

.*?

(无需转义正斜杠。)