Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if string has a single colon and that it's in the middle of the string

I am writing a bash script where I need to pass a parameter that follows a simple pattern: string:string.

  • Colon must be in the middle of the string
  • There must only be exactly one colon in the string

I found this question but it’s looking for the colon at the start of the string. I need the colon to be in the middle of the string and that there’s at most one colon in the string and nothing more. How do I make this check preferrably using regex?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To match any character except ":", use [^:]+ in regex. This regex expression should be able to match one and only one colon.

if [[ $var =~ ^[^:]+:[^:]+$ ]]; then echo "match"; fi
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading