문제

Kind of a groovy newbie so bear with me. I have a form that has a series of text fields. I’m filtering out two of those fields as well. This part works but the format for the values that gets returned isn’t how I would like it to be formatted. Should I be using toString or join or something else? I’m a groovy newbie so code samples would be much appreciated

Here’s my code:

String message = request.requestParameterMap.findAll { key, value ->!(key in [“userKey", "topicKey"]) }.toString()

Here’s my output:

[fname:[joey], lname:[bats], phone:[999-999-9999], email:[test@gmail.com]]

Here’s ideally how I’d like my output:

fname: joey
lname: bats
phone: 999-999-9999
email: test@gmail.com
도움이 되었습니까?

해결책

String message = 
    request.requestParameterMap
           .findAll { key, value ->!(key in [“userKey", "topicKey"]) }
           .collect { k, v -> "$k: ${v[0]}\n" }
           .join()

should give the message in expected format

fname: joey
lname: bats
phone: 999-999-9999
email: test@gmail.com

다른 팁

A quick and dirty way would be to use a series of replaceAll(...)s to format the code like you want it.

To replace the leading and trailing brackets:

message = message.replaceAll("^[|]$", "");

To replace opening brackets with a space:

message = message.replaceAll("\\[", " ");

And to replace closing brackets comma space with newline:

message = message.replaceAll("\\],\\s+", "\n");

It's very possible, even likely, that there exists some tool to format it quicker, but none that come to my mind.

Depending on what you want to do, you may prefer to split the string to get an array, but it really depends on what you're going to do with it.

Use inject to reduce the map to a string:

​def m = [​fname: 'joey', name: 'bats', phone: 999-999-9999, email: 'test@gmail.com']

m.inject("") { result, e ->
   result += "$e.key: $e.value\n"
   result
}

Results in:

fname: joey
name: bats
phone: -9999
email: test@gmail.com
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top