0

I have an array such as def list = ["pathfinding", " Gameplay", "Community"] which I would like to iterate and eliminate the whitespace at the beginning of each element. So I though it would be easy using something like:

for(x in list){
    x = x.replace("\\s", "")
    println x
}

but I keep getting this output

pathfinding
    Gameplay
Community

I do now know much about regex what I tried different ones I found here in SO and none worked so I guess the regex is not the problem here... any hints?

1
  • Groovy has method "".trim() if I remember correctly so you don't need to mess with regex. Commented Apr 27, 2021 at 18:23

5 Answers 5

6

Or you can just trim all the elements in the list

def trimmedList = list*.trim()
Sign up to request clarification or add additional context in comments.

Comments

1

Using replaceAll instead of replace works:

for (x in list) {     
    x = x.replaceAll("\\s", "")     
    println x
}

Comments

0

you can use String#trim()

def list = ["pathfinding", "    Gameplay", "Community"]
for(x in list){
    x = x.trim()
    log(x)
}

Comments

0

This is how I would trim leading space in Java:

public String trimLeadingWhitespace(String text) {

    Matcher matcher = PATTERN.matcher(text);
    if (matcher.find()) {
        return matcher.group(1);
    }
    else throw new RuntimeException("Unable to match pattern");
}

I am using regex to match the whitespace characters.

You can test the above code like this:

@Test
void shouldTrimLeadingWhitespace() {

    String[] array = new String[] { " pathfinding", "    Gameplay", "   Community" };
    for (String entry : array)
    {
        Assertions.assertTrue(entry.startsWith(" "));

        String trimmed = trimLeadingWhitespace(entry);
        Assertions.assertFalse(trimmed.startsWith("\\s"));

        System.out.println("Trimmed entry: " + trimmed);
    }
}

Comments

0

If you only want to trim the beginning and not the end, this is also a way:

def clean = list.collect { it.dropWhile { it == ' ' } }

running:

def list = ["pathfinding", "    Gameplay", "Community"]
def clean = list.collect { it.dropWhile { it == ' ' } }
println clean

prints:

─➤ groovy solution.groovy
[pathfinding, Gameplay, Community]

─➤

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.