@staticmethod def strSplit(textSource: str, patterns: str)->list: """ 分割字符串 :param textSource: :param patterns: :return: list """ ls = re.split(r'[' + patterns + '\s]', textSource) return ls @staticmethod def strFunSplit(textSource: str)->list: """ 分割字符串 用字符串函數 :param textSource: :return: list """ ls = textSource.split(" ") return ls @staticmethod def strRegSplit(textSource: str)->list: """ 分割字符串 :param textSource: :param patterns: :return: list """ ls = re.findall(r"\S+", textSource) return ls
#引用庫 import re 正則表達式的方式 #1.re.compile(): 該函數用於生成一個正則表達式,也就是匹配的核心部分,用來定義你需要怎麼匹配,匹配什麼內容,更多細節可以去參看菜鳥教程。 #2.re.findall(): 該函數用於在指定的字符串中進行匹配。 #str1 = 'lukfook8-hongkong+90shenzhen-4hh h7+8facai-shanghai geovindu' fullname=input("please enter full name:") firstname="" lastname="" ls=re.split(r'[-+' '.\s]', fullname) #print(re.split(r'[-+' '.\s]', str1)) # 以有+(加號)、-(減號)、' '(一個空格)、.(單字節英文點號) 字符串分割 print(type(ls)) for s in ls: print(s) #循環序列出列表中的字符串 firstname=ls[0] lastname=ls[1] print("firstname",firstname,",lastname:",lastname)
# encoding: utf-8 # 版權所有 2024 ©塗聚文有限公司 # 許可信息查看: # 描述: 正則表達式用法 # Author : geovindu,Geovin Du 塗聚文. # IDE : PyCharm 2023.1 python 311 # Datetime : 2024/4/28 10:37 # User : geovindu # Product : PyCharm # Project : EssentialAlgorithms # File : RegularString.py # explain : 學習 import re import os import sys class DuString(object): """ 正則表達式用法 """ @staticmethod def strSplit(textSource: str, patterns: str): """ 分割字符串 :param textSource: :param patterns: :return: list """ ls = re.split(r'[' + patterns + '\s]', textSource) return ls @staticmethod def getdit(textSrource : str) -> list: """ 提取數字數據 靜態方法 所有數值 數字提取:可以用正則表達式來提取數字,包括整數、浮點數等。 "去商店買了8個蘋果, 12斤香蕉, 共計12.85元." :return: """ pattern = r'\d+\.\d+|\d+' match = re.findall(pattern, textSrource) if match: print(match) # ['8', '12', '12.85'] else: print("未找到數值") return match @staticmethod def getint(textSource:str) ->list: """ 提取整數 :return: """ # 匹配浮點數的正則表達式 pattern = r'\d+' match = re.findall(pattern, textSource) if match: print(match) else: print("未找到數值") return match @staticmethod def getfloat(textSource:str) ->list: """ 提取浮點數 :return: """ # 匹配浮點數的正則表達式 pattern = r"\d+\.\d+" match = re.search(pattern, textSource) if match: float_number = float(match.group()) print(float_number) # else: print("未找到數值") return match @staticmethod def getDate(textSource:str)->list: """ 提取日期 處理邏輯: 年 4位有效數值 \d{4} 月 0-12 \d{1,2} 日 0-31 \d{1,2} """ date_text = "" if isinstance(textSource, str): regex_rule = r"(\d{4}-\d{1,2}-\d{1,2})" regex_pattern = re.compile(regex_rule) date_list = regex_pattern.findall(textSource) if date_list: date_text = date_list[0] return date_text @staticmethod def getTime(textSource:str)->list: """ 提取時間 :param textSource: :return: """ regexRule = r'(0?[0-9]|1[0-9]|2[0-3]):([0-5][0-9]|0?[0-9]):([1-5][0-9]|0?[0-9])' regexPattern = re.compile(regexRule) retList = regexPattern.findall(textSource) if retList: return retList else: print('沒有匹配成功.') return None @staticmethod def getUrl(textSource:str)->list: """ 提取網址 :param textSource: :return: """ # 定義一個正則表達式模式來匹配URL pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+' # 使用re.findall()函數找到所有匹配的URL urls = re.findall(pattern, textSource) return urls @staticmethod def getMainIs(textSource:str)->bool: """ 是否有效的郵件 :param textSource: :return: """ pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$' if re.match(pattern, textSource): print("有效的郵件地址") return True else: print("無效的郵件地址") return False @staticmethod def getIPIs(textSource:str)->bool: """ 是否有效的IP :param textSource: :return: """ #定義IPv4地址的正則表達式 ipv4_pattern = r'^((25[0-5]|2[0-4]\d|[01]?\d{1,2})\.){3}(25[0-5]|2[0-4]\d|[01]?\d{1,2})$' # 定義 IPv6 地址的正則表達式 ipv6_pattern = r'^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$' if re.match(ipv4_pattern, textSource): print("IPv4 地址") return True elif re.match(ipv6_pattern, textSource): print("IPv6 地址") return True else: print("無效的 IP 地址") return False @staticmethod def getChinaMobileIs(textSource:str)->bool: """ 是否有效的國內手機號碼 :param textSource: :return: """ # 匹配以1開頭,第二位是3、4、5、6、7、8或9,後面有9位數字的手機號碼。 pattern = r'^1[3456789]\d{9}$' for number in textSource: if re.match(pattern, number): print(f'{number} 是有效的手機號碼') return True else: print(f'{number} 不是有效的手機號碼') return False @staticmethod def getPostCodeIs(textSource:str)->bool: """ :param textSource: :return: """ pattern = r'^\d{6}$' # 匹配6位數字 if re.match(pattern, textSource): print("郵政編碼有效!") return True else: print("郵政編碼無效!") return False @staticmethod def getICDIs(textSource:str)->bool: pattern = r'^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}[0-9Xx]$' match = re.match(pattern, textSource) if match: print("身份證號碼合法!") return True else: print("身份證號碼不合法!") return False @staticmethod def extractHtmltags(textSource:str)->list: """ :param textSource: :return: """ pattern = r"<([^>]+)>" tags = re.findall(pattern, textSource) return tags @staticmethod def getStock(textSource:str)->list: """ :param textSource: :return: """ #text = "工商銀行(600886)\n\t 貴州茅臺(000123)" # 提取公司簡稱 companyNamePattern = r"[\u4e00-\u9fff]+" companyNameMatches = re.findall(companyNamePattern, textSource) companyCame = companyNameMatches if companyNameMatches else None # 提取證券代碼 6位數 stockCodePattern = r"\d{6}" stockCodeMatches = re.findall(stockCodePattern, textSource) stockCode = stockCodeMatches if stockCodeMatches else None print("公司簡稱:", companyCame) # 公司簡稱: ['工商銀行', '貴州茅臺'] print("證券代碼:", stockCode) # 證券代碼: ['600886', '000123'] return companyCame,stockCode
字符 |
含義 |
舉例 |
備註 |
符合條件 |
. |
一個任意字符 |
a..b |
a開頭b結尾,中間兩個任意字符 |
a|2b |
\w |
一個字母/數字/下劃線 |
\w... |
字母/數字/下劃線開頭 |
o8js |
\W |
非字母/數字/下劃線 |
\Wabc |
|
#abc |
\s |
一個空白字符 |
a\sb |
|
a\nb |
\S |
一個非空白字符 |
\S… |
三個數字 |
2jkh |
\d |
數字字符 |
\d\d\d |
|
675 |
\D |
非數字字符 |
\D\w\w\w |
|
#h7_ |
[] |
括號中任意一個字符[1-9]數字1到9 [a-z]小寫 [A-Z]大寫 |
[abc]aaa |
a/b/c開頭 |
caaa |
[^字符集] |
一個不在字符集中的任意字符 |
[^abc]... |
非a/b/c開頭 |
898i |
^ |
字符串開頭 |
^\ddid |
|
866 |
$ |
字符串結尾 |
abc$ |
|
abc |
\b |
(檢測邊界) |
Abc\b\saaa |
abclb\saaa |
abc aaa |
* |
匹配≥0次 |
\d* |
數字0或很多次 1個或很多個數字開 |
12312 |
+ |
匹配≥1次 |
\d+abc |
1個或很多個數字開頭 |
99abc |
? |
匹配0/1次 |
a?123 |
有a或者無a |
a123 |
{N} |
匹配N次 |
|
|
|
{M,N} |
匹配M到N次 |
|
|
|
{M,} |
至少匹配M次 |
|
|
|
{,N} |
最多匹配N次 |
|
|
|
|
|
|
|
|
https://docs.python.org/zh-cn/3.11//howto/regex.htmll
match()和search()都只匹配出一個符合條件的字符串,若想要所有,可以使用re.findall()
語法 |
釋義 |
| |
或者 |
() |
|
\ |
轉義符號,在特殊的符號前加\,來讓特殊的符號沒有意義不管在哪兒都需要轉義 -在口外面沒有特殊功能,在口中要表示-本身,就不要放在兩個字符之間()需要轉義 |
compile |
將正則表達式字符串轉換成正則表達式對象 |
fullmatch/match |
匹配對象或者None |
string |
獲取被匹配的原字符串 |
findall |
獲取字符串中滿足正則表達式的所有的子串,返回一個列表 |
finditer |
查找所有滿足正則條件的子串,返回值是迭代器,迭代器中的元素是匹配對象 |
split |
將字符串按照滿足正則表達式條件的子串進行分割 |
sub(正則,repl,字符串) |
字符串中滿足正則表達式條件的子串替換成repl。返回替換後的字符串 |
|
|