正则表达式前瞻和回顾后至多一个数字 [英] Regex Lookahead and lookbehind at most one digit

查看:582
本文介绍了正则表达式前瞻和回顾后至多一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在找创建正则表达式

  • 8字 [A-zA_Z]
  • 必须只包含一个数字串中的任何地方

我创造了这个模式:

  ^(?=。* [0-9]。* [0-9])[0-9A-ZA-Z] {8} $
 

此模式工作正常,但我想只允许一个数字。例如:

  aaaaaaa6比赛
aaa7aaaa比赛

aaa88aaa不匹配
aaa884aa不匹配
aaawwaaa不匹配
 

解决方案

你也可以使用:

  ^(?= [0-9A-ZA-Z] {8})[^ \ D] * \ D [^ \ D] * $
 

第一部分将断言,这场比赛包含8个字母或数字。一旦这被确保,第二部分确保有在比赛中只有一位数。

编辑:说明:

  • ^ $ 表示字符串的开始和结束。
  • (?= [0-9A-ZA-Z] {8})称,这场比赛包含8个字母或数字。
  • [^ \ D] * \ D [^ \ D] * 将意味着只有一个数字字符和其余的非数字字符。既然我们已经断言,输入中包含数字或字母,非数字字符这里有字母。

I'm looking for create RegEx pattern

  • 8 characters [a-zA_Z]
  • must contains only one digit in any place of string

I created this pattern:

^(?=.*[0-9].*[0-9])[0-9a-zA-Z]{8}$

This pattern works fine but i want only one digit allowed. Example:

aaaaaaa6   match
aaa7aaaa   match

aaa88aaa   don't match
aaa884aa   don't match
aaawwaaa   don't match

解决方案

You could instead use:

^(?=[0-9a-zA-Z]{8})[^\d]*\d[^\d]*$

The first part would assert that the match contains 8 alphabets or digits. Once this is ensured, the second part ensures that there is only one digit in the match.

EDIT: Explanation:

  • The anchors ^ and $ denote the start and end of string.
  • (?=[0-9a-zA-Z]{8}) asserts that the match contains 8 alphabets or digits.
  • [^\d]*\d[^\d]* would imply that there is only one digit character and remaining non-digit characters. Since we had already asserted that the input contains digits or alphabets, the non-digit characters here are alphabets.

这篇关于正则表达式前瞻和回顾后至多一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆