Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

c# - Regex to allow only these [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your expression is as follows:

^[a-zA-Z0-9~-_.]S{42,128}$

Let's break it down into its components:

  • ^ - Matches the beginning of the input.
  • [a-zA-Z0-9~-_.] - Match a single character a-z A-Z 0-9 ~ - _ or .
  • S - Matches any character except a white-space character.
  • {42,128} - Matches previous element at least 42 times and at most 128 times. In this case, the previous element is S.
  • $ - Matches the end of the input, or the point before a final at the end of the input.

Source for most definitions

So as we can see your regular expression currently does the following:

It first matches a single character a-z A-Z 0-9 ~ - _ or . at the start of the string. It then matches any non-whitespace character 42-128 times, and expects the end of the input to follow immediately afterwards. This means that we expect a string with a total length of 43-129 characters.

As your question states, you only want to match those specific characters, so your expression should actually be this (I've removed the S):

^[a-zA-Z0-9~-_.]{42,128}$

As for your specific input:

longenoughlongenoughlongenoughlongenoughlongenoughlongenoughlongenoughlongenoughAABSC__-......~~~.~-!

It appears that you have included an exclamation mark (!) at the end of your input, which of course doesn't match your constraint.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...