[英]Validate string in regular expression
I want to have a regular expression in JavaScript which help me to validate a string with contains only lower case character and and this character -
.我想在 JavaScript 中有一个正则表达式,它可以帮助我验证一个只包含小写字符和这个字符的字符串-
。
I use this expression:我使用这个表达式:
var regex = /^[a-z][-\s\.]$/
It doesn't work.它不起作用。 Any idea?任何想法?
Simple, just use: /^[az-]+$/
简单,只需使用: /^[az-]+$/
Explanation:解释:
^
: Match from beginning string ^
: 从字符串开始匹配[az-]
: Match all character between az and - [az-]
: 匹配 az 和 - 之间的所有字符
[]
: Only characters within brackets are allowed []
:只允许括号内的字符az
: Match all character between az. az
:匹配 az 之间的所有字符。 Ex: p,s,t例如:p,s,t-
: Match only strip ( -
) character -
:仅匹配带 ( -
) 字符+
: Shorthand for {1,}
. +
: {1,}
的简写。 The means is match 1 or more手段是匹配1个或更多$
: Match until end of the string $
: 匹配直到字符串结束Example:例子:
const regex= /^[az-]+$/ console.log(regex.test("abc")) // true console.log(regex.test("aBcD")) // false console.log(regex.test("ac")) // true
Try this:尝试这个:
var regex = /^[-a-z]+$/;
var regex = /^[-az]+$/; var strs = [ "a", "aB", "abcd", "abcde-", "-", "-----", "abc", "aDc", " " ]; strs.forEach(str=>console.log(str, regex.test(str)));
Try this尝试这个
/^[a-z-]*$/
it should match the letters az or - as many times as possible.它应该尽可能多地匹配字母 az 或 -。
What you regex does is trying to match az one single time, followed by any of -, whitespace or dot one single time.您正则表达式所做的是尝试一次匹配 az,然后一次匹配 -、空格或点中的任何一个。 Then expect the string to end.然后期望字符串结束。
Use this regular expression:使用这个正则表达式:
let regex = /^[a-z\-]+$/;
Then:然后:
regex.test("abcd") // true
regex.test("ab-d") // true
regex.test("ab3d") // false
regex.test("") // false
PS: If you want to allow empty string ""
to pass, use /^[az\-]*$/
. PS:如果要允许空字符串""
通过,请使用/^[az\-]*$/
。 Theres an *
instead of +
at the end.最后有一个*
而不是+
。 See Regex Cheat Sheet: https://www.rexegg.com/regex-quickstart.html请参阅正则表达式备忘单: https://www.rexegg.com/regex-quickstart.html
This will work:这将起作用:
var regex = /^[az|\-|\s]+$/ //For this regex make use of the 'or' | operator str = 'test- '; str.match(regex); //["test- ", index: 0, input: "test- ", groups: undefined] str = 'testT- ' // string now contains an Uppercase Letter so it shouldn't match anymore str.match(regex) //null
I hope this helps我希望这有帮助
var str = 'asdadWW--asd'; console.log(str.match(/[az]|\-/g));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.