You are viewing limited content. For full access, please sign in.

Question

Question

Regex to test string for length and that it contains at least one period

asked on October 5, 2023

Hi.  I need help figuring out a regex that would test a string to make sure it's at least 8 characters in length and has at least one period in it.

Sample values:

1000.1528.E1 - this one should pass the regex as it is at least 8 characters in length and has at least one period

1528.E1 - this would fail the regex due to length

1000,1528,E1 - this would fail the regex due to commas instead of periods

Thanks for any assistance!

 

0 0

Answer

SELECTED ANSWER
replied on October 5, 2023

This doesn't look right to me, so I ran it on https://regex101.com/ which says that the ones that are supposed to match don't match. In particular, "\.$" means that the input needs to end with a period. This is a pretty tricky regex to write because for the length matching you don't care what the characters are, but you have a global requirement to satisfy. That is a case for a lookahead matcher. I think this works:

^(?=.*\.).{8,}$

(Disclaimer: I used Bard also)

0 0

Replies

replied on October 5, 2023

Here's what Google Bard AI says:

The following regular expression will test a string to make sure it's at least 8 characters in length and has at least one period in it:

^.{8,}\.$

This regex can be broken down as follows:

  • ^ matches the beginning of the string.
  • .{8,} matches any sequence of characters that is at least 8 characters long.
  • \. matches a single period.
  • $ matches the end of the string.

Here are some examples of how the regex would match different strings:

String | Match
------- | --------
1000.1528.E1 | Yes
1528.E1 | No
1000,1528,E1 | No
0 0
replied on October 5, 2023

Neat...I'll have to try that tool!

 

0 0
SELECTED ANSWER
replied on October 5, 2023

This doesn't look right to me, so I ran it on https://regex101.com/ which says that the ones that are supposed to match don't match. In particular, "\.$" means that the input needs to end with a period. This is a pretty tricky regex to write because for the length matching you don't care what the characters are, but you have a global requirement to satisfy. That is a case for a lookahead matcher. I think this works:

^(?=.*\.).{8,}$

(Disclaimer: I used Bard also)

0 0
replied on October 6, 2023

I wasn't able to get Craig's answer to work so I'll try this one today.  Thanks!

0 0
replied on October 6, 2023

Brian, your suggestion worked.  I'm also checking out Bard to refine the regex further and it seems to be working pretty well.  Thanks!

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.