正则表达式 - 提取 1 到 8 个字符之间且不包含超过 2 个字母的文本 ([A-Za-z])

Regex- Extract a text that is between 1 and 8 chars and does not contain more than 2 letters ([A-Za-z])

我想使用正则表达式提取 1 到 8 个字符且不包含超过 2 个字母 ([A-Za-z]) 的文本。

例如:

Valid: "12A-32B" from the text "Register:12A-32B Index:A"
Invalid: "12 Index" from the text "Register:12 Index:A"

在此示例中,提取的文本应以文本 "Register" 作为边界。

我尝试使用 positive/negative 前瞻但无济于事。

谢谢。

试试这个正则表达式:

^(?!.*[A-Za-z].*[A-Za-z].*[A-Za-z])[A-Za-z0-9-]{1,8}$

这将匹配最多包含 8 个数字或字母的任何字符串,字符串中最多出现 2 个字母。

您可能需要一个额外的步骤来提取原始文本中的文本。您可以尝试使用此正则表达式:

Register:(.*) Index

我们可以尝试对所有内容使用一个正则表达式,但这会很复杂。从您的应用程序层使用两个步骤可能会更容易。

Demo

我找到了解决方案

  1. 使用注册开始定界符提取文本

  2. 将此正则表达式与提取的文本一起使用:

    ^(.{1,8}?)(?<![A-Za-z]{3})( |$)