如何在 Python 中使用正則表示式匹配字串開頭?
Python 中的正則表示式是一組字元,允許您使用搜索模式查詢字串或一組字串。RegEx 是正則表示式的簡稱。
要在 Python 中使用正則表示式,請使用re包。
要使用正則表示式匹配 Python 中字串的開頭,我們使用^/w+正則表示式。
這裡,
- ^表示以…開頭。
- /w返回一個匹配,其中字串包含任何單詞字元(a z、A Z、0 9 和下劃線字元)。
- +表示一個或多個字元出現。
使用 re.search() 方法
在下面的示例程式碼中,我們匹配單詞tutorialspoint,它位於字串“tutorialspoint is a great platform to enhance your skills”的開頭。
我們首先匯入正則表示式模組。
import re
然後,我們使用了search()函式,該函式從 re 模組匯入以獲取所需的字串。Python 中的re.search()函式搜尋字串以查詢匹配項,如果存在任何匹配項,則返回匹配物件。group()方法用於返回匹配的字串部分。
示例
import re s = 'tutorialspoint is a great platform to enhance your skills' result = re.search(r'^\w+', s) print (result.group())
輸出
執行上述程式後,將獲得以下輸出。
tutorialspoint
示例 2
現在,讓我們使用 Python 中的 re.search() 方法找出單個字串的第一個字母。
import re s = 'Program' result = re.search(r"\b[a-zA-Z]", s) print ('The first letter of the given string is:',result.group())
輸出
The first letter of the given string is: P
使用 re.findall() 方法
Python 中的 findall(pattern, string) 方法查詢字串中模式的每次出現。當您使用模式“^\w+”時,插入符號 (^) 保證您只匹配字串開頭的 Python 單詞。
示例
import re text = 'tutorialspoint is a great platform to enhance your skills in tutorialspoint' result = re.findall(r'^\w+', text) print(result)
輸出
子字串“tutorialspoint”出現兩次,但在字串中只有一個位置與之匹配,即開頭,如下面的輸出所示。
['tutorialspoint']
示例
現在,讓我們使用 Python 中的 re.findall() 方法找出單個字串的第一個字母。
import re s = 'Program' result = re.findall(r"\b[a-zA-Z]", s) print ('The first letter of the given string is:',result)
輸出
The first letter of the given string is: ['P']
廣告