Jump to content

replaceAll() Function


This topic is 3896 days old. Please don't post here. Open a new topic instead.

Recommended Posts

you are passing a string with a comma in, the function requires two values

 

try this

import java.util.regex.*

text = 'Test One Two'
code = 'One,Box'
regex = rep.split(',')

result = text.replaceAll(regex[0], regex[1] )
Link to comment
Share on other sites

Eden

The error message gives the clue as to what is expected, and what was given...

You will notice that the 'method' replaceAll can take different types of arguments as well as the simple string, string you are using. But everything you pass to the Groovy comes in as a string and needs to be converted to the required object first.

 

This method would allow you to use a Regex as the first input - but only if you created a regex.Pattern object from the string first, otherwise it would literally look for say 'd+t' in the text rather than digit(s) followed by a tab character.

import java.util.regex.Pattern

pattern = 'd+t'
regex = Pattern.compile(pattern)

The Groovy pages have a great example with closure as the second argument which capitalises each word and makes the rest of it lowercase
 
text.replaceAll('w+',
        { it[0].toUpperCase() + ((it.size() > 1) ? it[1..-1].toLowerCase() : '') }))

This says

for each word (w+), take the first character (it[0]) and Uppercase it, then if the size of the word is more than 1 (it.size() > 1) add the second to the last characters (it[1..-1]) lowercased to it else add nothing (: '')

 
Link to comment
Share on other sites

This topic is 3896 days old. Please don't post here. Open a new topic instead.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.