简体   繁体   English

Java正则表达式-仅匹配一次

[英]java regex - match one occurrences only

I have this pattern "[A-Za-z -]*" that I'm using when validating input fields: 验证输入字段时,我使用的是“ [A-Za-z-] *”模式:

if (input.matches("[A-Za-z -]*")) {
   return true;
} else {
   return false;
}

Basically, I'm checking if the inputs are within my field validation requirements (letters, space, and dash (allow one dash only)). 基本上,我正在检查输入内容是否在我的字段验证要求之内(字母,空格和破折号(仅允许一个破折号))。 My problem is I should return true only if it has letters, space, and dash (ONE DASH only), my current code returns true even if I have inputted a lot of dashes. 我的问题是,只有当它包含字母,空格和破折号(仅一个破折号)时,我才应该返回true;即使输入了很多破折号,我当前的代码也返回true。 How can I restrict my pattern to detect if dash exceeds one? 如何限制图案检测破折号是否超过一个?

The following is equivalent to your regex, except that it allows at most one dash: 以下内容与您的正则表达式相同,不同之处在于它最多允许一个破折号:

[A-Za-z ]*-?[A-Za-z ]*

This matches zero or more letters/spaces, followed by at most one dash, followed by zero or more letters/spaces. 这匹配零个或多个字母/空格,后跟最多一个破折号,后跟零个或多个字母/空格。

Start by removing a dash. 首先删除破折号。

if(input.indexOf('-') != 0) input.replaceFirst("-", " ");

Then, since you've only removed one dash, you can run your regex query without checking for hyphens. 然后,由于只删除了一个破折号,因此您可以运行正则表达式查询而无需检查连字符。 If one exists, the query will return false. 如果存在,查询将返回false。

在输入开始处使用锚定的否定前瞻:

^(?!(.*-){2})[A-Za-z -]*

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

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