Any Regex wizards on here?

Author
Discussion

StephenP

Original Poster:

1,906 posts

217 months

Monday 19th August
quotequote all
I'm not sure if this is even possible with a regex but I'm trying to test if a string contains a minimum number of a specific character.

For example, if I want 3 or more '1's in the text to equal true...

1100000000000000 = false
1000101000000000 = true
1111111111111111 = true

If possible, I'm trying to avoid changing some code that already has a test in place where the variable and Regex values are both passed in to the program.

Google hasn't helped with my basic Regex skills! biggrin

EddieSteadyGo

13,156 posts

210 months

Monday 19th August
quotequote all
I'd use ChatGPT for that type of question. You can create a free account and still get access to GPT4-o which is the latest model.

Just pasting your exact post gives the following response. With some finessing I think you could get exactly what you need.

https://chatgpt.com/share/df477631-3179-454d-a11e-...

Also worth trying Claude Sonnet, which is another LLM. I've found it better than ChatGPT on a number of occasions.

https://claude.ai/new

danpalmer1993

508 posts

115 months

Monday 19th August
quotequote all
I think this should work but it's been a while since I did any regex.

^(?:[^1]*1){3}[^1]*$

StephenP

Original Poster:

1,906 posts

217 months

Monday 19th August
quotequote all
That works perfectly! Never even thought of using ChatGPT to generate it so thanks for the suggestion thumbup

tribbles

4,022 posts

229 months

Monday 19th August
quotequote all
danpalmer1993 said:
I think this should work but it's been a while since I did any regex.

^(?:[^1]*1){3}[^1]*$
Seems a bit complicated, unless I'm missing something...

1.*1.*1

Should do the trick. 1, followed by 0 or more of anything, followed by 1, and then 0 or more of anything with a 1.

This should occur anywhere within the string, so don't need to start at the start of the string, nor end with the end. And if there's more than 3 '1's, it'll still be true.

biggiles

1,836 posts

232 months

Tuesday 20th August
quotequote all
tribbles said:
danpalmer1993 said:
I think this should work but it's been a while since I did any regex.

^(?:[^1]*1){3}[^1]*$
Seems a bit complicated, unless I'm missing something...

1.*1.*1

Should do the trick. 1, followed by 0 or more of anything, followed by 1, and then 0 or more of anything with a 1.

This should occur anywhere within the string, so don't need to start at the start of the string, nor end with the end. And if there's more than 3 '1's, it'll still be true.
I'd agree with Tribbles, this is a simple regex use case, no need to reach for ChatGPT for this one.