Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match a string containing a comma (eg 1,5)

Tags:

java

regex

i want to check if the string i take from a Textfield has a comma, in order to drop it and ask for a new value with dot.

i try to use

  textTestAr.trim().matches("^[,]+$")     

but nothing happens, while this

        ^[1-9,]+$      

does the trick, but also matches numbers like 1.

like image 925
Rentonie Avatar asked Dec 11 '12 13:12

Rentonie


People also ask

How do you match a comma in regex?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.

How do I match a specific character in regex?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ).

How do you create a string in regex?

Example : ^\d{3} will match with patterns like "901" in "901-333-". It tells the computer that the match must occur at the end of the string or before \n at the end of the line or string. Example : -\d{3}$ will match with patterns like "-333" in "-901-333". A character class matches any one of a set of characters.

Can you use or in regex?

Alternation is the term in regular expression that is actually a simple “OR”. In a regular expression it is denoted with a vertical line character | . For instance, we need to find programming languages: HTML, PHP, Java or JavaScript.


3 Answers

You don't need to force regular expressions on this problem. A simple textTestAr.indexOf(',') will do.

like image 109
Marko Topolnik Avatar answered Oct 23 '22 22:10

Marko Topolnik


The caret ^ matches the beginning of the text. [,]+ matches an arbitrary number of commas. What you need is something to ignore everything before and after the item you are looking for:

^.*[,].*$

The dot matches any character except newline. * is repetition (0 -- any number). The $ matches the end of text.

Note that trimming the string is unnecessary here.

like image 34
krlmlr Avatar answered Oct 23 '22 21:10

krlmlr


Why not use String#contains instead of regex here.

like image 35
anubhava Avatar answered Oct 23 '22 23:10

anubhava