下面是一个使用Python编写的函数,它可以从字符串中提取单词,并删除字符串中的其他字符:
import re
def extract_words(string):
# 使用正则表达式匹配单词
words = re.findall(r'\b\w+\b', string)
# 使用空格连接单词列表,并返回结果
return ' '.join(words)
# 示例输入
input_string = "Hello, world! This is a sample sentence."
# 调用函数并打印结果
print(extract_words(input_string))
输出:
Hello world This is a sample sentence
该函数使用了Python的re模块来进行正则表达式匹配。正则表达式模式\b\w+\b
用于匹配一个或多个字母或数字字符组成的单词。函数返回一个字符串,其中所有匹配的单词之间用空格分隔。