![](/img/trans.png)
[英]If cell has 2 words, extract only 1st word and if cell has 3 words, extract 2 first words - PANDAS/REGEX
[英]Regex to extract ONLY alphanumeric words
我正在寻找一个正则表达式来提取仅包含字母数字字符的单词:
string = 'This is a $dollar sign !!'
matches = re.findall(regex, string)
matches = ['This', 'is', 'sign']
这可以通过标记字符串并使用以下正则表达式分别评估每个标记来完成:
^[a-zA-Z0-9]+$
由于性能问题,我希望能够在不标记整个字符串的情况下提取字母数字标记。 我最接近的是
regex = \b[a-zA-Z0-9]+\b
,但仍提取包含字母数字字符的子字符串:
string = 'This is a $dollar sign !!'
matches = re.findall(regex, string)
matches = ['This', 'is', 'dollar', 'sign']
是否有正则表达式能够实现这一目标? 我尝试了不同的方法,但无法提出解决方案。
除了单词边界之外,还可以向后和向前查找空格(或字符串的开头/结尾):
(?:^|(?<= ))[a-zA-Z0-9]+(?= |$)
https://regex101.com/r/TZ7q1c/1
请注意,“ a”是一个独立的字母数字单词,因此也包含在内。
['This', 'is', 'a', 'sign']
无需为此使用正则表达式,python具有内置的isalnum
字符串方法。 见下文:
string = 'This is a $dollar sign !!'
matches = [word for word in string.split(' ') if word.isalnum()]
[感谢Khabz的评论进行编辑。 我误解了这个问题]
根据您的意图,您也可以“拆分”而不是“匹配”。
>>> matches = re.split(r'(?:\s*\S*[\$\!]+\S*\s*|\s+)', string)
['This', 'is', 'a', 'sign', '']
并且如果您需要删除前导或结尾的空字符串:
>>> matches = [x for x in re.split(r'(?:\s*\S*[\$\!]+\S*\s*|\s+)', a) if x ]
['This', 'is', 'a', 'sign']
SomePerformance的使用前后观察的响应是最紧凑的。 当指定了排除项时,使用split有时是有优势的,即上面的正则表达式描述了需要排除的内容。 但是,在这种情况下,指定的是字母数字,因此使用split()不是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.