Search code examples
javatrim

Trim from a space or tab onward or backwards in Java


I know how to trim things in Java but how does one trim from a space or tab to the left or to the right? I have a program that searches for some 4 character prefixes let’s say this prefix is XYBC then it has X amount of characters to it like XYBC4975723434 but the line that my code takes looks like this:

Viuhaskfdksjfkds XYBC4975723434 fkdsjkfjaksjfklsdakldjsen

But then I would like it to trim it to this: XYBC4975723434 Thanks


Solution

  • That is not a trim, but a regular expression find, using the following regex:

    \bXYBC.*?\b
    

    That expression used word boundaries, which may not be what you want.

    For whitespace, use:

    (?<=^|\s)XYBC\S*
    

    Test

    public static void main(String[] args) {
        test("Viuhaskfdksjfkds  XYBC4975723434 fkdsjkfjaksjfklsdakldjsen");
        test("XYBC4975723434");
        test("Viuhaskfdksjfkds  xXYBC4975723434 fkdsjkfjaksjfklsdakldjsen");
        test("abc XYBC49-75(723)4$34 xyz");
    }
    private static void test(String text) {
        Matcher m = Pattern.compile("\\bXYBC.*?\\b").matcher(text);
        if (m.find()) {
            System.out.println(m.group());
        } else {
            System.out.println("Not found: " + text);
        }
    }
    

    Output (word boundary)

    XYBC4975723434
    XYBC4975723434
    Not found: Viuhaskfdksjfkds  xXYBC4975723434 fkdsjkfjaksjfklsdakldjsen
    XYBC49
    

    Output (whitespace)

    XYBC4975723434
    XYBC4975723434
    Not found: Viuhaskfdksjfkds  xXYBC4975723434 fkdsjkfjaksjfklsdakldjsen
    XYBC49-75(723)4$34