Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式模式包括字母、特殊、数字_Python_Regex_Nltk_Special Characters_Numeric - Fatal编程技术网

Python 正则表达式模式包括字母、特殊、数字

Python 正则表达式模式包括字母、特殊、数字,python,regex,nltk,special-characters,numeric,Python,Regex,Nltk,Special Characters,Numeric,以下是我的句子: 例: 这是第一个示例:示例234- 这是第二个(示例)3451 这是我的第三个例子(456)3 预期产出: ['this is first: example', 234, -] ['this is second (example)', 345, 1] ['this is my third example', (456), 3] 我厌倦了使用python、nltk单词标记和句子标记、split()和 str1=re.compile('([\w:]+)|([0-9])) str1

以下是我的句子: 例:

这是第一个示例:示例234-

这是第二个(示例)3451

这是我的第三个例子(456)3

预期产出:

['this is first: example', 234, -]
['this is second (example)', 345, 1]
['this is my third example', (456), 3]
我厌倦了使用python、nltk单词标记和句子标记、split()和

str1=re.compile('([\w:]+)|([0-9]))
str1.findall(“我上面的例子”)


请向我推荐一个模块,该模块可以提供我的预期输出,或者让我知道我在regex中的错误在哪里。使用您的表达式,您将获得单独的匹配,因为有替换。如果一行上有三个部分的组,只需创建一个与整行匹配的表达式,并分别捕获这三个组。比如说

^(.*) ([\d()]+) ([-\d])
请注意,这是因为当
*
匹配整行时,引擎会回溯并放弃字符以匹配末尾的数字组

代码:

regex = r"^(.*) ([\d()]+) ([-\d])"
matches = re.findall(regex, your_text, re.MULTILINE)
print(matches)
输出:

[('this is first: example', '234', '-'), 
('this is second (example)', '345', '1'), 
('this is my third example', '(456)', '3')]
编辑

如果您知道最后会有多少组数字,那么上述模式效果很好。但是,如果该数字是可变的,则需要创建一个静态数量的重复可选数字组,如
(?:\d+)
,以预测必须匹配的值的数量,但这很麻烦,可能仍然无法满足弹出的所有要求

因此,更好的选择是在一个块中捕获源中发生的所有数字,然后将其拆分。为此,我们将使用惰性量词匹配字符串的开头,以允许匹配字符串末尾的所有可用数字组,我们将在一个字符串中捕获这些数字组。例如:

^(.*)((?:[-\d()]+)+)$

然后,我们可以将捕获的一组数字拆分为一个数组,并将其包含在描述中。示例代码:

重新导入
测试_str=(
“这是第一个示例:示例234-\n”
“这是第二个(示例)345 1\n”
“这是我的第三个示例(456)3\n”
“这是第四个示例(456)4 12\n”
“这是第五个示例300 1 16 200(2)18”)
regex=r“^(.*)(?:[-\d()]+)+)$”
matches=re.findall(regex、test\u str、re.MULTILINE)
在匹配项中为(a,b)捕获=[(a,b.split())]
打印(捕获)
输出:

[('this is first: example', '234', '-'), 
('this is second (example)', '345', '1'), 
('this is my third example', '(456)', '3')]
[
('this is first:example',['234','-']),
(‘这是第二个(示例)’,['345','1']),
(‘这是我的第三个例子’,[‘456’,‘3’),
(‘这是第四个例子’,[‘456’,‘4’,‘12’),
(‘这是第五个例子’,[‘300’、‘1’、‘16’、‘200’、‘2’、‘18’))
]

谢谢您的时间@oriberu。这种方法真的很好,从头开始。出于好奇再问一个问题,我们有一个包含上述示例内容的test1.txt,一个包含4个不同值(例如:这是第一个:示例345 1 321)或5或6个值的test2.txt。那么,我们如何用这种方法解决这个问题呢。一个表达式解多个types@Eswarthammana我编辑了我的答案来回答你的问题;请看一看。谢谢你教regex@oriberu。在演示站点中,我尝试了另外一个示例以及其他示例-仅字符串,不带数字以下是^(.*)(?:[-\d()]+)+)$@Eswarthammana,我不确定我是否理解,但我认为这是因为character类中的附加字符。你能告诉我你的意思吗?您可以编辑演示并单击左侧的
updateregex
;然后你会得到一个新的链接,你可以在这里发布。