简体   繁体   English

以 2 个字母开头并以 3 个字母结尾的匹配正则表达式

[英]Regex for match beginning with 2 letters and ending with 3 letters

Example input:示例输入:

'Please find the ref AB45676785567XYZ. which is used to identify reference number'

Example output:示例输出:

'AB45676785567XYZ'

I need a RegExp to return the match exactly matching my requirements;我需要一个RegExp来返回完全符合我要求的匹配项; ie the substring where the first 2 and last 3 characters are letters.即前 2 个和后 3 个字符是字母的子串。

The first 2 and last 3 letters are unknown.前 2 个和后 3 个字母未知。

I've tried this RegExp :我试过这个RegExp

[a-zA-Z]{2}[^\s]*?[a-zA-Z]{3}

But it is not matching as intended.但它不符合预期。

Your current RegExp matches the following words marked with code blocks:您当前的RegExp匹配以下标有代码块的单词:

Please find the ref AB45676785567XYZ . Please找到参考AB45676785567XYZ which is used to identify reference number用于identify reference number

This is because your RegExp , [a-zA-Z]{2}[^\\s]*?[a-zA-Z]{3} , is asking for:这是因为您的RegExp[a-zA-Z]{2}[^\\s]*?[a-zA-Z]{3}要求:

  • [a-zA-Z]{2} Begins with 2 letters (either case) [a-zA-Z]{2}以 2 个字母开头(无论大小写)
  • [^\\s]*? Contains anything that isn't a whitespace包含任何不是空格的内容
  • [a-zA-Z]{3} Ends with 3 letters (either case) [a-zA-Z]{3}以 3 个字母结尾(无论大小写)

In your current example, restricting the letters to uppercase only would match only the match you seek:在您当前的示例中,将字母限制为仅大写只会匹配您寻找的匹配项:

[A-Z]{2}[^\s]+[A-Z]{3}

Alternatively, requiring numbers between the 2 beginning and 3 ending letters would also produce the match you want:或者,要求 2 个开始和 3 个结束字母之间的数字也会产生您想要的匹配:

[a-zA-Z]{2}\d+[a-zA-Z]{3}

Start with 2 letters :以 2 个字母开头:

[a-zA-Z]{2}

Digits in the middle :中间的数字:

\d+

Finish with 3 letters :以 3 个字母结束:

[a-zA-Z]{3}

Full Regex :完整的正则表达式:

[a-zA-Z]{2}\d+[a-zA-Z]{3}

If the middle text is Alpha-Numeric, you can use this :如果中间的文本是字母数字,你可以使用这个:

[A-Z]{2}[^\s]+[A-Z]{3}

What is really important here, is word boundaries \\b , try: \\b[a-zA-Z]{2}\\w+[a-zA-Z]{3}\\b这里真正重要的是字边界\\b ,尝试: \\b[a-zA-Z]{2}\\w+[a-zA-Z]{3}\\b

Explanation:解释:

\\b - word boundary \\b - 词边界

[a-zA-Z]{2} - match any letter, 2 times [a-zA-Z]{2} - 匹配任意字母,2 次

\\w+ - match one or more word characters \\w+ - 匹配一个或多个单词字符

[a-zA-Z]{3} - match any letter, 3 times [a-zA-Z]{3} - 匹配任意字母,3 次

\\b - word boundary \\b - 词边界

Demo演示

CAUTION your requirements are amibgious, as any word consisting of 5 or more letters would match the pattern注意您的要求是模棱两可的,因为任何由 5 个或更多字母组成的单词都将匹配该模式

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

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