-1

I have the following string value;

 String value = "col = at, ud = sam, col = me, od = tt, col = fg";

I need to return only col = at col = me, and col = fg;

I know I could use:

value.substring(0, value.indexOf(",")

to return col = at but I'm not sure how to get all three. Thanks for any help.

mattt
  • 45
  • 5
  • Are there always only two letters after the `col = `? – GBlodgett Jul 24 '18 at 19:47
  • no its varies, I just simplified them for this example – mattt Jul 24 '18 at 19:48
  • 1
    Could you maybe split by `",\\s+"`, then by `"\\s+=\\s+"`, and pick up any pairs where the first element is `"col"`? Would that work for you? – Dawood ibn Kareem Jul 24 '18 at 19:49
  • 1
    @matt are you just trying to pull the value after the = sign or the entire col = – basic Jul 24 '18 at 19:49
  • I im trying to pull the entire col = – mattt Jul 24 '18 at 19:50
  • Sorry, I mean `*` instead of `+` in each of those regular expressions in my earlier comment. – Dawood ibn Kareem Jul 24 '18 at 19:56
  • Your input string looks suspiciously like an [LDAP Distinguished Name](https://ldap.com/ldap-dns-and-rdns/). If that's really what it is, consider using a specialized parser that will handle escape sequences, etc. Java has some [built-in utility classes](https://docs.oracle.com/javase/tutorial/jndi/newstuff/ldapname.html) for parsing LDAP names. – dnault Jul 24 '18 at 20:07

1 Answers1

1

It can be achieved with Streams:

List<String> results = Arrays.stream(value.split(","))
.map(String::trim)
.filter(val-> !val.isEmpty() && val.startsWith("col ="))
.collect(Collectors.toList())

You can also use a regex:

String value = "col = at, ud = sam, col = me, od = tt, col = fg";

Pattern pattern = Pattern.compile("col\\s+=\\s+\\w++");

List<String> allMatches = new ArrayList<String>();
Matcher m = pattern.matcher(value);
while (m.find()) {
   allMatches.add(m.group());
}
allMatches.forEach(System.out::print); 

Output:

col = at col = me col = fg

Beri
  • 11,470
  • 4
  • 35
  • 57