简体   繁体   中英

Easy way to tell if a string is contained in another string that is a comma delimited list

I am working in Talend so need a one-liner if possible to determine if string1 is a value in string2 which is a comma delimited list.

For example string1=foo and string2=foo,bar,red,green it would be true.

I was using contains but the issue is it matches on string2=fool,bar,red,green... in this case I want false

boolean result = Arrays.asList(string2.split(",")).contains(string1);

This is one approach, but depends on timeComplexity requirements as well. Using regex can be another approach

Another option using regex is:

String string1 = "\\bfoo\\b";                
String string2 = "bar, foo ,red,green";        

System.out.println(Pattern.compile(string1).matcher(string2).find());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM