匹配至少一个小写字母和至少一个大写字母

时间:2016-08-11 13:32:12

标签: regex grep regex-lookarounds

我试图用一个约束提取单词[a-zA-Z]+:一个单词必须包含至少一个小写字母和至少一个大写字母(在单词内的任何位置)。示例:如果输入为hello 123 worLD,则唯一匹配应为worLD

我尝试使用这样的积极前瞻:

echo "hello 123 worLD" | grep -oP "(?=.*[a-z])(?=.*[A-Z])[a-zA-Z]+"
hello

这是不正确的:唯一的匹配是hello而不是worLD。然后我尝试了这个:

echo "hello 123 worLD" | grep -oP "\K((?=.*[a-z])(?=.*[A-Z])[a-zA-Z]+)"
hello
worLD

这仍然不正确:hello不应匹配。

2 个答案:

答案 0 :(得分:4)

前瞻中的.*不仅检查相邻单词中的字母存在,还检查字符串后面的字母存在。使用[a-zA-Z]*

echo "hello 123 worLD" | grep -oP "\\b(?=[A-Za-z]*[a-z])(?=[A-Za-z]*[A-Z])[a-zA-Z]+"

请参阅demo online

我还在开头添加了一个单词边界\b,以便仅在单词边界之后执行超前检查。

答案 1 :(得分:1)

答案:

import MySQLdb
import sys

if len(sys.argv) != 4:
        print "please enter the Hostname to connect followed by:"
        print "mysql username;"
        print "mysql db to connect;"
else:
        _host = sys.argv[1]
        _user = sys.argv[2]
#       _pass = sys.argv[3]
        _db   = sys.argv[3]
        cham = raw_input("please enter the command to be executed:- ")
        _pass = raw_input("please enter password:- ")

        if cham == "drop table":
            db = MySQLdb.connect(host = _host, user = _user,db =  _db, passwd = _pass )
            cursor = db.cursor()
            cursor.execute("show tables")
            for i in cursor.fetchall():
                cursor.execute("drop table" + " " + (i[0]))
                print cursor.fetchall()
                print "all the tables has been deleted"
            db.close()
        else:
            db = MySQLdb.connect(host = _host, user = _user,db =  _db, passwd = _pass )
            cursor = db.cursor()
            cursor.execute(cham)
            print cursor.fetchall()
            db.close()

演示:https://ideone.com/HjLH5o

<强>解释

首先检查单词是以一个或多个大写字母后跟一个小写字母开头,反之亦然,后跟任意顺序的任意数量的小写和大写字母。

<强>性能:

This solution需要31步才能在提供的测试字符串上达到匹配,而accepted solution需要47步。

相关问题