简体   繁体   English

RegEx 允许所有字符,长度应为 1-50 个字符

[英]RegEx to allow all characters, length should be 1-50 characters

Issue问题

I am trying to implement a Regular Expression that will check a string is between 1 - 50 characters.我正在尝试实现一个正则表达式来检查字符串是否在 1 - 50 个字符之间。 They are allowed to enter any characters.他们可以输入任何字符。

I am new to creating regex expressions but this is my attempt: ^{1,50}$我是创建正则表达式的新手,但这是我的尝试: ^{1,50}$

The reason I tried that is that I found this was the way to limit the characters.我尝试这样做的原因是我发现这是限制字符的方法。

Any help on this would be great.对此的任何帮助都会很棒。

Try ^.{1,50}$试试^.{1,50}$

Explanation:说明:

  • . dot stands for all characters.点代表所有字符。 Except \\n for which you will have to use s DOTALL flag.除了\\n您必须使用s DOTALL 标志。

Regex101 Demo Regex101 演示

Regular Expression Options 正则表达式选项

For the Exact Length of the String you could use对于您可以使用的字符串的确切长度

^.{50}$

Whereas to check the Length Range you can use而要检查您可以使用的长度范围

^.{5,50}$

It might be more sensible for real users if I also included a lower limit on the number of letters如果我还包括字母数量的下限,对于真实用户来说可能更明智

If you wanted to just check the Minimum Length you can use如果您只想检查可以使用的最小长度

^.{50,}$

Now a string of at least fifty letters, but extending to any length,现在是至少五十个字母的字符串,但可以扩展到任意长度,

^.{0,50}$

This will match a whole string containing between 0 and 50 (inclusive) of any character.这将匹配包含 0 到 50(含)之间的任何字符的整个字符串。 Though regular expressions are probably the wrong tool for this job.尽管正则表达式可能是这项工作的错误工具。 Regex is overkill , just check the length of the string.正则表达式是矫枉过正,只需检查字符串的长度。 You should have used String.Length for this like你应该使用String.Length这样的

if(UrString.Length > 0 && UrString.Length <= 50)

How about just inspecting the Length of the string?只检查字符串的Length怎么样?

string str = "less than 50 chars";
if(str.Length > 0 && str.Length <= 50)
{
    // yay, we've got a winner
}

I suggest我建议

.{1,50}

To generate regex expressions you can use Expresso , which is a free .NET regular expression development tool.要生成正则表达式,您可以使用Expresso ,它是一个免费的 .NET 正则表达式开发工具。 Using this program, you will be able to build complex regular expressions just by selecting its different components from a menu.使用此程序,您只需从菜单中选择不同的组件,就可以构建复杂的正则表达式。 You can test the created expressions entering values to them.您可以测试创建的表达式输入值。

To allow all characters you use .要允许您使用的所有字符. in regex.在正则表达式中。

So, to have a max 50 char string you'd do:因此,要获得最多 50 个字符的字符串,您可以:

^.{1,50}$

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

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