如何在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
然後,我們使用了從re模組匯入的search()函式來獲取所需的字串。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']
廣告