简体   繁体   English

我怎样才能在正则表达式中限制点一次或可选

[英]how can I limit dot only once or optional in regex

A regex is needed which should have only special character dot which should either be optional or occur only once.需要一个正则表达式,它应该只有特殊字符点,它应该是可选的或只出现一次。

pattern = /^([A-Za-z.]+)$/;

Without more information I'd use如果没有更多信息,我会使用

/^(?!$)[a-z]*\.?[a-z]*$/i

The negative lookahead prevents empty matches.先行防止空匹配。

See this demo at regex101请参阅 regex101 上的演示

Here are some ways to do it:以下是一些方法:

  1. Deal separately where the input has has one dot, with optional letters surrounding it, or no dot (but then having at least one letter):分别处理输入有一个点、周围有可选字母或没有点(但至少有一个字母)的地方:

    /^([az]*\.[az]*|[az]+)$/i

  1. Just capture letters and dots like you did, but don't allow the input to have two dots, using a negative look ahead:像你一样捕捉字母和点,但不允许输入有两个点,使用负向展望:

    /^(?.(.*\.){2})([az.]+)$/i

  2. Capture optional letters then an optional point and then optional letters, but forbid an empty input with a negative look-ahead:捕获可选字母,然后是可选点,然后是可选字母,但禁止带有否定前瞻的空输入:

    /^(?.$)([az]*\??[az]*)$/i

If in any case the dot should not be at the start or end and not match an empty string, you can start the match with 1 or more chars az and then optionally match a dot and again 1 or more chars az:如果在任何情况下点不应该在开头或结尾并且不匹配空字符串,您可以用 1 个或多个字符 az 开始匹配,然后可选地匹配一个点并再次匹配 1 个或多个字符 az:

/^[a-z]+(?:\.[a-z]+)?$/i

Regex demo正则表达式演示

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

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