简体   繁体   English

如何完全或部分匹配python中的正则表达式

[英]How to match a regex in python, either completely or partially

This is a basic question but I've searched a bit and am still having doubts. 这是一个基本问题,但我进行了搜索,仍然有疑问。

Let's take the following regex as an example: 让我们以以下正则表达式为例:

regex_example = re.compile('\d{10}\s\d-\d{3}-\d{3}-\d{4}')

Now let's imagine there is a string which may contain substrings matching the full length of that regex, such as '1234567890 1-123-456-7890' or it may just contain substrings that match the first part of the regex, say for example '1234567890 1-123'. 现在,我们假设有一个字符串,其中可能包含与该正则表达式的全长匹配的子字符串,例如“ 1234567890 1-123-456-7890”,或者可能仅包含与正则表达式的第一部分匹配的子字符串,例如“ 1234567890 1-123'。

I would like to modify the regex (or use another solution) allowing me to match any substring that has 14 or more char and matches the regex either partially or entirely. 我想修改正则表达式(或使用其他解决方案),以允许我匹配具有14个或更多char的任何子字符串,并部分或完全匹配正则表达式。 So my code would find: 所以我的代码会发现:

'1234567890 1-1' (has 14 characters and matches the start of the regex) or '1234567890 1-13' or '1234567890 1-134' '1234567890 1-1'(具有14个字符并与正则表达式的开头匹配)或'1234567890 1-13'或'1234567890 1-134'

And so forth, up to the full length of the regex. 依此类推,直到正则表达式的全长。

You can make part after first 14 characters optional: 您可以在前14个字符后选择部分:

regex_example = re.compile(
   '(\d{10}\s\d-\d(?:\d{0,2}(?:(?:-\d{0,3})?(?:-\d{0,4})?)?)?)')

RegEx Demo 正则演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM