Groovy文本两次分割报错:MissingMethodException问题咨询
Fixing Your Groovy MissingMethodException Issue
Hey there, let's break down what's going wrong and get your code working as intended.
What's Causing the Error?
That groovy.lang.MissingMethodException is popping up because you're trying to call the split() method on an array—and arrays don't have that method! Here's the breakdown:
- When you run
contact.split('-'), the result (contact_part) is aString[](an array of strings), not a single string. - Your line 15
contact_part.split('\\n')is trying to use a string method on an array, which Groovy doesn't recognize. That's exactly why you're getting the missing method error.
Corrected Code for Your Requirement
Your goal is to split the contact string by - into 3 separate entries, then print each one on a new line. Here's the working code:
def contact = '''name1 Function1 : 1111 : name1@mail.com-name2 Function2 : 2222 : name2@mail.com-name3 Function3 : 3333 : name3@mail.com ''' // Split the original string into an array of contact entries using '-' def contactParts = contact.split('-') // Join the array elements with newlines and print them (each entry on its own line) println contactParts.join('\n') // Optional: If you want to clean up extra whitespace at the start/end of each entry // contactParts.each { entry -> // println entry.trim() // }
Quick Explanation
split('-'): This correctly slices your original string into an array where each element is a full contact entry (name, role, number, email).join('\n'): This takes the array of contact entries and glues them together with newline characters, so when you print, each entry shows up on its own line—exactly what you wanted.- The optional
trim()call cleans up any stray spaces at the start or end of each entry, making your output look neater.
内容的提问来源于stack exchange,提问作者Wijdane
相关产品推荐
相关产品推荐

