Andrew Curtis
Andrew Curtis

Reputation: 15

Regex in java that parses strings that only contain a specific character while allowing spaces

So i'm currently trying to search for strings that have the comma , in it, while allowing spaces in between. For example, a ,,,, , ,, , , ,, b c d will have the entirety between a and b be highlighted, but not between b and c, or c and d.

currently, I have regex like this:

([]\\,+[\s]?)+ 

that highlights all spaces and commas, but it will even highlight the spaces between b and c, and c and d. How do i make it so that it only highlights where there are commas?

also, this specific regex does not work in Java. Where do I have to escape character to make it functional in Java as well?

Upvotes: 1

Views: 61

Answers (1)

Pshemo
Pshemo

Reputation: 124225

It looks like you are looking for regex like

\s*,[\s,]+

which in Java needs to be written as String "\\s*,[\\s,]*" (\ is special character in String as well as in regex and to create such literal you need to escape it by writing it as "\\").

This regex will accept only text which contains of spaces and commas, but must have at least one comma, so parts between b and c, or c and d shouldn't be matched because they don't contain at least one comma.

Upvotes: 1

Related Questions