我有帶有下面給出的示例文本的 pandas 列,需要從文本中提取固定長度的識別符號
df1=pd.DataFrame({'Incident_details':['324657_Sample text1 about the incident',
' 316678_sample text2 with details of incident',
'*DEPARTMENT LIST 316878-Sample text3 with information, ph: 01314522345',
'327787_34587621 (sample text4 with incident details)',
'Sample text5 with details',
'327997_1000587621 (sample text6 with incident info',
' 314489_incident text7 details',
'DEPARTMENT_LIST_325489_Text8 details',
'DEPARTMENT3_316489 text9 details',
'DEPARTMENT_LIST_326499',
'324512_1000257218',
'314656_text10(01345782345)',
'324757_03456789',
'DEPARTMENT_CDES_324903_35678910 (details text11)',
'326512_34500257218 - text12 details',
'Incident 325621_ 316512_ sample text 13']})
- 我需要提取的識別符號始終以 3 開頭,固定長度為 6 位。
- 它可以出現在字串的開頭或空格之后(單個或兩個或三個空格)或下劃線之后。
- 給定字串中可以有多個 id 并且需要下面的輸出。

目前我正在使用
df1['Incident_id'] = df1['incident_details'].str \
.findall(r'(?:^|\s|[^_])(\d{6})').str.join(", ")
這個運算式沒有為我的要求提供正確的輸出。
uj5u.com熱心網友回復:
像這樣的東西會起作用:
(?:^|(?<=\D))3\d{5}(?=\D|$)
(?:^|(?<=\D))- 在我身后是行首或非數字字符- Python 不支持可變寬度的lookbehinds,所以我不能使用這個變體:
(?<=^|\D)
- Python 不支持可變寬度的lookbehinds,所以我不能使用這個變體:
3\d{5}- 數字 3 后跟五位數字(?=\D|$)- 在我前面是一個非數字字符或行尾
https://regex101.com/r/8AoWeK/1
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/524446.html
標籤:正则表达式细绳提炼数字
上一篇:如何在使用txt檔案和字典時從字串末尾洗掉'\n'?
下一篇:如何根據某些條件從字串中洗掉字符
