Python程序提取字符串直到第一个非字母数字字符
给定一个字符串,在第一次出现非字母数字之前提取所有字母数字。
Input : test_str = ‘geek$s4g!!!eeks’
Output : geek
Explanation : Stopped at $ occurrence.
Input : test_str = ‘ge)eks4g!!!eeks’
Output : ge
Explanation : Stopped at ) occurrence.
方法 #1:使用正则表达式 + search()
在此,search() 用于搜索适当的 regex() 以查找字母数字,然后将结果切片直到第一次出现非字母数字字符
Python3
# Python3 code to demonstrate working of
# Extract string till first Non-Alphanumeric character
# Using regex + search()
import re
# initializing string
test_str = 'geeks4g!!!eeks'
# printing original string
print("The original string is : " + str(test_str))
# using start() to get 1st substring
res = re.search(r'\W+', test_str).start()
res = test_str[0 : res]
# printing result
print("The resultant string : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract string till first Non-Alphanumeric character
# Using findall()
import re
# initializing string
test_str = 'geeks4g!!!eeks'
# printing original string
print("The original string is : " + str(test_str))
# using findall() to get all substrings
# 0th index gives 1st substring
res = re.findall("[\dA-Za-z]*", test_str)[0]
# printing result
print("The resultant string : " + str(res))
输出
The original string is : geeks4g!!!eeks
The resultant string : geeks4g
方法 #2:使用 findall()
这是解决此问题的另一种正则表达式方法。在此,我们通过访问第 0 个索引来提取非 anum字符之前的第一个子字符串。
蟒蛇3
# Python3 code to demonstrate working of
# Extract string till first Non-Alphanumeric character
# Using findall()
import re
# initializing string
test_str = 'geeks4g!!!eeks'
# printing original string
print("The original string is : " + str(test_str))
# using findall() to get all substrings
# 0th index gives 1st substring
res = re.findall("[\dA-Za-z]*", test_str)[0]
# printing result
print("The resultant string : " + str(res))
输出
The original string is : geeks4g!!!eeks
The resultant string : geeks4g