How to extract substring in Groovy? - string

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

Related

JS QUESTION: how can i make it so that when im detecting a word inside a string, i check standalone words like Hello

How do i check for the word "Hello" inside a string in an if statement but it should only detect if the word "Hello" is alone and not like "Helloo" or "HHello"
The easiest way to do such thing is to use regular expressions. By using regular expressions you can define a rule in order to validate a specific pattern.
Here is the rule for the pattern you required to be matched:
The word must contain the string "hello"
The string "hello" must be preceded by white-space, otherwise it must be the found at the beginning of the string to be matched.
The string "hello" must be followed by either a '.' or a white-space, Otherwise it must be found at the end of the string to be matched.
Here is a simple js code which implements the above rule:
let string = 'Hello, I am hello. Say me hello.';
const pattern = /(^|\s)hello(\s|.|$)/gi;
/*const pattern = /\bhello\b/ you can use this pattern, its easier*/
let matchResult = string.match(pattern);
console.log(matchResult);
In the above code I assumed that the pattern is not case sensitive. That is why I added case insensitive modifier ("i") after the pattern. I also added the global modifier ("g") to match all occurrence of the string "hello".
You can change the rule to whatever you want and update the regular expression to confirm to the new rule. For example you can allow for the string to be followed by "!". You can do that by simply adding "|!" after "$".
If you are new to regular expressions I suggest you to visit W3Schools reference:
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
One way to achieve this is by first replacing all the non alphabetic characters from string like hello, how are you #NatiG's answer will fail at this point, because the word hello is present with a leading , but no empty space. once all the special characters are removed you can simply split the string to array of words and filter 'hello' from there.
let text = "hello how are you doing today? Helloo HHello";
// Remove all non alphabetical charachters
text = text.replace(/[^a-zA-Z0-9 ]/g, '')
// Break the text string to words
const myArray = text.split(" ");
const found = myArray.filter((word) => word.toLowerCase() == 'hello')
// to check the array of found ```hellos```
console.log(found)
//Get the found status
if(found.length > 0) {
console.log('Found')
}
Result
['hello']
Found

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"

Groovy replace everything after character

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"' )

Powershell: convert string to number

I have an Array where some drive data from WMI are captured:
$drivedata = $Drives | select #{Name="Kapazität(GB)";Expression={$_.Kapazität}}
The Array has these values (2 drives):
#{Kapazität(GB)=1.500} #{Kapazität(GB)=1.500}
and just want to convert the 1.500 into a number 1500
I tried different suggestions I found here, but couldn't get it working:
-Replace ".","" and [int] doesn't work.
I am not sure if regex would be correct and how to do this.
Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).
Give this method a try:
[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)
$intNum
Simply divide the Variable containing Numbers as a string by 1. PowerShell automatically convert the result to an integer.
$a = 15; $b = 2; $a + $b --> 152
But if you divide it before:
$a/1 + $b/1 --> 17
Since this topic never received a verified solution, I can offer a simple solution to the two issues I see you asked solutions for.
Replacing the "." character when value is a string
The string class offers a replace method for the string object you want to update:
Example:
$myString = $myString.replace(".","")
Converting the string value to an integer
The system.int32 class (or simply [int] in powershell) has a method available called "TryParse" which will not only pass back a boolean indicating whether the string is an integer, but will also return the value of the integer into an existing variable by reference if it returns true.
Example:
[string]$convertedInt = "1500"
[int]$returnedInt = 0
[bool]$result = [int]::TryParse($convertedInt, [ref]$returnedInt)
I hope this addresses the issue you initially brought up in your question.
I demonstrate how to receive a string, for example "-484876800000" and tryparse the string to make sure it can be assigned to a long. I calculate the Date from universaltime and return a string. When you convert a string to a number, you must decide the numeric type and precision and test if the string data can be parse, otherwise, it will throw and error.
function universalToDate
{
param (
$paramValue
)
$retVal=""
if ($paramValue)
{
$epoch=[datetime]'1/1/1970'
[long]$returnedLong = 0
[bool]$result = [long]::TryParse($paramValue,[ref]$returnedLong)
if ($result -eq 1)
{
$val=$returnedLong/1000.0
$retVal=$epoch.AddSeconds($val).ToString("yyyy-MM-dd")
}
}
else
{
$retVal=$null
}
return($retVal)
}
Replace all but the digits in the string like so:
$messyString = "Get the integer from this string: -1.500 !!"
[int]$myInt = $messyString -replace '\D', ''
$myInt
# PS > 1500
The regex \D will match everything except digits and remove them from your string.
This will work fine for your example.
It seems the issue is in "-f ($_.Partition.Size/1GB)}}" If you want the value in MB then change the 1GB to 1MB.

Best way to compare multiple string in java

Suppose I have a string "That question is on the minds of every one.".
I want to compare each word in string with a set of word I.e. (to , is ,on , of) and if those word occurs I want to append some string on the existing string.
Eg.
to = append "Hi";
Is = append "Hello";
And so on.
To be more specific I have used StringTokenizer to get the each word and compared thru if else statement. However we can use Switch also but it is available in Jdk 1.
7.
I don't know if this is what you mean, but:
You could use String.split() to separate the words from your string like
String[] words = myString.split(" ");
and then, for each word, compare it with the given set
for(String s : words)
{
switch(s)
{
case("to"):
[...]
}
}
Or you could just use the String.contains() method without even splitting your string, but I don't know if that's what you wanted.
Use a HashMap<String,String> variable to store your set of words and the replacement words you want. Then split your string with split(), loop through the resulting String[] and for each String in the String[], check whether the HashMap containsKey() that String. Build your output/resulting String in the loop - if the word is contained in the HashMap, replace it with the value of the corresponding key in the HashMap, otherwise use the String you are currently on from the String[].

Resources