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

Regex java check for String with only commas

i try to accomplish to check if a String only contains comma.

i tried

^[,][,*]
'^[,\\,]'

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

'^[,][,]$'' but this works only with a string like ",," and not with ",,,,"

what am i doing wrong?

>Solution :

Hey you can use this regex ^[,]+$

Or even simplify it to ^,+$


Note that we don’t need to wrap , inside character set like [,] as it doesn’t give us anything (it also doesn’t improve readability of regex for programmers).

Character sets [...] are usually used as shorter version of alternation for single characters. For instance instead of (?:a|b|c|d|e) we can write [abcde] or even [a-e]. BUT using character set for single character makes no sense EXCEPT when it is meant to be used as escape mechanism – to make some special character represent only itself. For instance dot . in regex can match any character, but if we escape it and write regex like ab[.]cd it will only match ab.cd and not abXcd since now [.] can only match dot itself.

But escaping comma also makes no sense here since , is not special character in this context, so it doesn’t require escaping. Comma can be special character, but only inside quantifiers like {min,} or {min,max} for instance {2,} or {2,10} but that is not the case here.

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