I want to create a regular expression which will:
我想要创建一个正则表达式
- not contain any space and special characters except "-" and "_"
- 除“-”和“_”外,不包含任何空格和特殊字符
- it should contain at least one alphabet character
- 它应该包含至少一个字母字符。
The regular expression I created is:
我创建的正则表达式是:
^[^/\s/]+[a-z]{1,}[0-9]*[\-\_]*[^\/][^/\s/]$
It only only matches if my string contains at least 4 characters, including 1 alphabet. I tried it on https://regex101.com/#javascript Can someone help me what I am doing wrong here.
它只匹配如果我的字符串包含至少4个字符,包括1个字母。我在https://regex101.com/#javascript上尝试过,可以有人帮助我在这里做错了什么。
2 个解决方案
#1
2
You need to learn about lookaround. One solution to your problem is:
你需要了解周围的情况。你的问题的一个解决办法是:
/(?=^[\w-]{4,}$)(.*[a-z].*)/gmi
-
(?=^[\w-]{4,}$)
will assert that you input will contains only chars in the range a-z, digit,_
and ,-
with a length of at least 4. - {4}$)将断言您的输入将只包含a-z、数字、_和-的范围内的字符,长度至少为4。
-
(.*[a-z].*)
ensure that there will be at least one char in the range a-z. - (.*)确保在a-z范围内至少有一个字符。
See Demo
看到演示
#2
1
Using fundamental regex primitives, you can use this:
使用基本的regex原语,您可以使用以下方法:
/^[0-9_-]*[a-z]+[0-9a-z_-]*$/i
It works correctly with these sample input strings:
它可以正确地使用这些示例输入字符串:
- 999c123-
- 999 c123 -
- a123-88asd
- a123 - 88 asd
- 9923--_b
- 9923年,_b
- B
- B
- 99-luftballoons
- 99 - luftballoons
- Z8f
- Z8f
And does not match these strings:
与这些字符串不匹配:
- 999
- 999年
- -51-
- -51 -
- ---_-
- ——_
It's fast and will work in pretty much every regex engine, even non-standard (non-extended) grep.
它的速度很快,而且将在几乎所有的regex引擎,甚至非标准(非扩展)grep中工作。
#1
2
You need to learn about lookaround. One solution to your problem is:
你需要了解周围的情况。你的问题的一个解决办法是:
/(?=^[\w-]{4,}$)(.*[a-z].*)/gmi
-
(?=^[\w-]{4,}$)
will assert that you input will contains only chars in the range a-z, digit,_
and ,-
with a length of at least 4. - {4}$)将断言您的输入将只包含a-z、数字、_和-的范围内的字符,长度至少为4。
-
(.*[a-z].*)
ensure that there will be at least one char in the range a-z. - (.*)确保在a-z范围内至少有一个字符。
See Demo
看到演示
#2
1
Using fundamental regex primitives, you can use this:
使用基本的regex原语,您可以使用以下方法:
/^[0-9_-]*[a-z]+[0-9a-z_-]*$/i
It works correctly with these sample input strings:
它可以正确地使用这些示例输入字符串:
- 999c123-
- 999 c123 -
- a123-88asd
- a123 - 88 asd
- 9923--_b
- 9923年,_b
- B
- B
- 99-luftballoons
- 99 - luftballoons
- Z8f
- Z8f
And does not match these strings:
与这些字符串不匹配:
- 999
- 999年
- -51-
- -51 -
- ---_-
- ——_
It's fast and will work in pretty much every regex engine, even non-standard (non-extended) grep.
它的速度很快,而且将在几乎所有的regex引擎,甚至非标准(非扩展)grep中工作。