-2

I have a line like :

[Something-26543] Done some quite heavy job here.

Can someone advice if there is a a way to grep only the line between the square brackets. Before:

[Something-26543] Done some quite heavy job here.

After filtering:

Something-26543
WhoAmI
  • 1,013
  • 2
  • 9
  • 19
  • Please add the code you have tried and how it failed (e.g. errors, stacktraces, logs, ...) so we can improve on it. – cfrick Mar 29 '21 at 08:04
  • I haven't added a code, cause question is "how it can be done". Are those questions forbidden? – WhoAmI Mar 29 '21 at 08:05
  • Does this answer your question? [Finding words within a string in Java](https://stackoverflow.com/questions/32672371/finding-words-within-a-string-in-java) – the Hutt Mar 29 '21 at 08:26

1 Answers1

2

the easiest way to do this is using regex. In java it should be something like this. matcher.group(1) should be what you are looking for. This code is untested, to learn more about regex I use this site : https://regex101.com/

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String[] args) {
        final String regex = "\\[(.*?)\\]";
        final String string = "[Something-26543] Done some quite heavy job here.";
        
        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);
        
        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }
    }
}
Connor Stoop
  • 1,574
  • 1
  • 12
  • 26