Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to find value in comma separated string (Java/Android)

Assuming a String as defined:

String list = "apples,orange,bears,1,100,20,apple";

Without separating the list out into a collection or array, is there a better way to find a String in the list? For instance, if I search for "bear", there should be no result, since there would be no exact match (bears doesn't count). You can't look for ",bear," since there's no guarantee that the word bear would not appear at the beginning or end of the file.

like image 487
StackOverflowed Avatar asked Jan 29 '26 12:01

StackOverflowed


2 Answers

You could still use something like:

(^|,)bears(,|$)

It will look for the commas, or the beginning or end of the line, which I believe is what you're looking for.

EDIT: Addendum

Since Denomales mentioned it, the above regex search will consume any commas (if any) that it can find, so that you will get overlapping matches in the case of lists like apples,orange,bears,honey,bears,bears,bears,bears,9999,bees and will count only 3 bears out of the 5 present. What you can do in this case is use lookarounds. It might take a bit to get your head around them, but the gist of it is that they look behind, or ahead of characters without consuming them. This thus makes it possible to find all the 5 bears, and this is how you use them:

(?<=^|,)bears(?=,|$)

A breakdown of characters...

^ means the beginning of a line, so that in case there are no commas, you will still get a match.

, is a literal comma.

(?<= ... ) is a positive lookbehind and will look behind the b character in bears to make sure there is what's inside, that is either a ^ or a ,.

(?= ... ) is a positive lookahead and will look after the s character in bears to make sure there is what's inside, that is either a , or a $.

$ means the end of a line, working very much like ^, but at the end.

like image 196
Jerry Avatar answered Jan 31 '26 01:01

Jerry


You can use a lookahead and a lookbehind to check what is around the searched word without capturing * . Example:

 Pattern p = Pattern.compile("(?<=,|^)bears(?=,|$)");

(* however if you want to only check the presence of the word "bears", it isn't very important)

like image 29
Casimir et Hippolyte Avatar answered Jan 31 '26 01:01

Casimir et Hippolyte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!