Groovy replace everything after character - groovy

I need to replace all content after a specific character in groovy with the value of a parameter,
my string is :
env.APP_VERSION="1.9"
And I would like to replace everything after the = sign with the value of a certain parameter let's call it $PARAM.
I was able to trim everything after the = sign,
but not replace it...
result = result.substring(0, result.indexOf('APP_VERSION='));
any help would be appreciated.

One of possible solutions is, indeed, to use regex. It should include:
(?<==) - A positive lookbehind for =.
.* - Match all chars (up to the end).
So the script can look like below:
src = 'env.APP_VERSION="1.9"'
PARAM = '"xyz"'
res = src.replaceFirst(/(?<==).*/, PARAM)
Another solution is to split the string on = and "mount" the result string
from:
The first string from split result.
= char.
Your replacement string.
This time the processing part of the script should be:
spl = src.split('=')
res = spl[0] + '=' + PARAM

Without knowing about your original intentions you have 2 options:
1) Do not reinvent the wheel and use GString magic:
String ver = '1.9'
String result = "env.APP_VERSION=\"$ver\""
2) use some regex:
result = result.replaceFirst( /APP_VERSION="[^"]+"/, 'APP_VERSION="something"' )

Related

Substring after a character

I'm looking for a way to beautifully extract 'user id' from string in Groovy. Lets say I have string "key::${userId}" For example:
String s = "key::123456"
I can extract userId in java style as following
Long.parseLong(s.substring(s.indexOf("::") + 2))
But I believe that there is a way to make it shorter and more neatly
If key:: is always the prefix, you can use the - operator, combined with the as keyword for the String to long conversion:
String s = 'key::123456'
long userId = (s - 'key::') as long
You can use multiple assignment operator combined with tokenize method:
def (_,userId) = "key::123456".tokenize("::")
assert userId == "123456"

Remove part of string (regular expressions)

I am a beginner in programming. I have a string for example "test:1" and "test:2". And I want to remove ":1" and ":2" (including :). How can I do it using regular expression?
Hi andrew it's pretty easy. Think of a string as if it is an array of chars (letters) cause it actually IS. If the part of the string you want to delete is allways at the end of the string and allways the same length it goes like this:
var exampleString = 'test:1';
exampleString.length -= 2;
Thats it you just deleted the last two values(letters) of the string(charArray)
If you cant be shure it's allways at the end or the amount of chars to delete you'd to use the version of szymon
There are at least a few ways to do it with Groovy. If you want to stick to regular expression, you can apply expression ^([^:]+) (which means all characters from the beginning of the string until reaching :) to a StringGroovyMethods.find(regexp) method, e.g.
def str = "test:1".find(/^([^:]+)/)
assert str == 'test'
Alternatively you can use good old String.split(String delimiter) method:
def str = "test:1".split(':')[0]
assert str == 'test'

Groovy split on period and return only first value

I have the input as
var = primarynode.domain.local
and now I Need only primarynode from it.
I was looking both split and tokenize but not able to do it in one line code. does anyone know how to do it in one line code?
Well assuming that you want to just get the first word(before . )
from the input string.
You can use the tokenize operator of the String
If you have
def var = "primarynode.domain.local"
then you can do
def firstValue = ​var.tokenize(".")[0]​
println firstValue
output
primarynode
The split method works, you just have to be aware that the argument is a regular expression and not a plain String. And since "." means "any character" in a regular expression, you'll need to escape it...
var = 'primarynode.domain.local'.split(/\./)[0]
...or use a character class (the "." is not special inside a character class)
var = 'primarynode.domain.local'.split(/[.]/)[0]

Replacing Numeric Characters through Indexing

I'm attempting to replace a character within a string, which in this case is a digit, with another digit that has been incremented by 1, and then adding it back to the original string and replacing the previous digit character.
In the below snippet, sams2 should become sams3 after this code has executed
However, I keep receiving the error, Unable to index into an object of type System.String. Is it not possible to replace characters through indexing? Is there a better methodology for something like this?
$SAMAccountName = "sams2"
$lastChar = $SAMAccountName.Length - 1
[int]$intNum = [convert]::ToInt32($SAMAccountName[$lastChar])
$convertedChar = [convert]::ToString($intNum + 1)
$SAMAccountName[$lastChar] = $convertedChar
This would only work if the incremental number is one digit.
$SAMAccountName = "sams2"
$partOne = $SAMAccountName.SubString(0, $SAMAccountName.Length - 1)
$partTwo = [int]$SAMAccountName.SubString($SAMAccountName.Length - 1, 1) + 1
$SAMAccountName = "$partOne$partTwo"
Ok, this is a two step process. First we get the number off the end, then we replace that number in the string.
'sams2' |%{
$Int = 1+ ($_ -replace "^.*?(\d+)$",'$1')
$_ -replace "\d+$",$Int
}
Maybe try regular expressions and groups and then be able to handle multi-digits for free...
$SAMAccountName = "sam2"
# use regex101.com for help with regular expressions
if ($SAMAccountName -match "(.*?)(\d+)")
{
# uncomment for debugging
#$Matches
$newSAMAccountName = $Matches[1] + (([int]$Matches[2])+1)
$newSAMAccountName
}
There are a couple of things to note in your code:
Strings are immutable. New instance of string is created every time some change is made.
Use StringBuilder to manipulate individual chars.
Make sure you have compatible types. String is not char.
Take a look at following snippet:
$SAMAccountName = "sams2"
$sb = [System.Text.StringBuilder]$SAMAccountName
$lastChar = $SAMAccountName.Length - 1
[int]$intNum = [convert]::ToInt32($SAMAccountName[$lastChar])
$covertedChar = [convert]::ToChar($intNum + 1)
$sb[$lastChar] = $covertedChar
[string]$sb
You can also use another metod, like following one:
$SAMAccountName = "sams2"
$SAMAccountName.Substring(0, $SAMAccountName.Length-1)+([int]$SAMAccountName.Substring($SAMAccountName.Length-1, 1)+1)

How to extract substring in Groovy?

I have a Groovy method that currently works but is real ugly/hacky looking:
def parseId(String str) {
System.out.println("str: " + str)
int index = href.indexOf("repositoryId")
System.out.println("index: " + index)
int repoIndex = index + 13
System.out.println("repoIndex" + repoIndex)
String repoId = href.substring(repoIndex)
System.out.println("repoId is: " + repoId)
}
When this runs, you might get output like:
str: wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514
index: 59
repoIndex: 72
repoId is: 31850514
As you can see, I'm simply interested in obtaining the repositoryId value (everything after the = operator) out of the String. Is there a more efficient/Groovier way of doing this or this the only way?
There are a lot of ways to achieve what you want. I'll suggest a simple one using split:
sub = { it.split("repositoryId=")[1] }
str='wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514'
assert sub(str) == '31850514'
Using a regular expression you could do
def repositoryId = (str =~ "repositoryId=(.*)")[0][1]
The =~ is a regex matcher
or a shortcut regexp - if you are looking only for single match:
String repoId = str.replaceFirst( /.*&repositoryId=(\w+).*/, '$1' )
All the answers here contains regular expressions, however there are a bunch of string methods in Groovy.
String Function
Sample
Description
contains
myStringVar.contains(substring)
Returns true if and only if this string contains the specified sequence of char values
equals
myStringVar.equals(substring)
This is similar to the above but has to be an exact match for the check to return a true value
endsWith
myStringVar.endsWith(suffix)
This method checks the new value contains an ending string
startsWith
myStringVar.startsWith(prefix)
This method checks the new value contains an starting string
equalsIgnoreCase
myStringVar.equalsIgnoreCase(substring)
The same as equals but without case sensitivity
isEmpty
myStringVar.isEmpty()
Checks if myStringVar is populated or not.
matches
myStringVar.matches(substring)
This is the same as equals with the slight difference being that matches takes a regular string as a parameter unlike equals which takes another String object
replace
myStringVar.replace(old,new)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar
replaceAll
myStringVar.replaceAll(old_regex,new)
Replaces each substring of this string that matches the given regular expression with the given replacement
split
myStringVar.split(regex)
Splits this string around matches of the given regular expression
Source

Resources