Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 8232
  • Last Modified:

How to use Regular Expression to check for minimum string length


Hi,

How do I use a Regular Expression to find out  if a string is at least N characters?

Thanks.
0
l_agmon
Asked:
l_agmon
  • 3
  • 2
1 Solution
 
manav_mathurCommented:
/^.{5}$/

or

/^.....$/



0
 
manav_mathurCommented:
Sorry didnt read 'atleast'.

/^.{5}.*
/^......*$/    (remember to put 6 dots, * stands for any number of including 0)
0
 
manav_mathurCommented:
Im sorry, was in a bad state while replying, so assumed it as 5.

/^.{N}.*/   replace N with the number of characters. AFAIK, you cannot use a variable here in a $ format.

second option is
/^......*/  - but do remember to put N+1 dots. This is because * works on the last dot and it means, any number of any character including zero characters. . so N dots means N characters and follow it by a .* for any number of characters including zero. So the whole thing reads like, N characters followed by any number of characters.....

Cheers,
Manav
0
 
DominicCroninCommented:
Of course, the correct answer to your question depends on which regex language you are using. It's not uncommon for a regex language to allow you to specify "both ends"  of an interval quantifier. Using several dots is one possibility, but let's assume Perl regexes for a moment. The interval quantifier allows you to say {n,m} meaning match n to m times. This means that

.{5,}

will match at least 5 characters. In perl this would look like:

/.{5,}/

Note that manav's use of anchors (^ and *) isn't necessary if all you want to do is check that the string is at least that long. Still - I suppose you want to make this part of some more complicated test. Using regexes just to check a string length is overkill. Most programming languages (all programming languages??) have simpler ways to get the length of a string.
0
 
DominicCroninCommented:
I think the correct answer is "you shouldn't". Anyway - sufficient good suggestions have been given to award the points and PAQ the question.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now