Groovy: remove specific characters from end of string - groovy

I have a string that might end with multiple \n (the two symbols, not a newline).
How can I remove that from the end of the string?
For example: abc\ndef\n\n should become abc\ndef
Thanks

For such a simple task a simple trim() would suffice:
assert 'abc\ndef' == 'abc\ndef\n\n\n\n'.trim()

You can do it like this:
s = "abc\ndef\n\n"
assert s.replaceAll(/\n*$/, "") == "abc\ndef"
The section between // looks for any amount of \n and the $ represents the end of the string. So, replace any amount of newlines with nothing else after them, with an empty string.

Related

Remove comma at the end of a string [duplicate]

Input
str = 'test1,test2,test3,'
Ouput
str = 'test1,test2,test3'
Requirement to strip the last occurence of ','
Just use rstrip().
result = your_string.rstrip(',')
str = 'test1,test2,test3,'
str[:-1] # 'test1,test2,test3'
The question is very old but tries to give the better answer
str = 'test1,test2,test3,'
It will check the last character, if the last character is a comma it will remove otherwise will return the original string.
result = str[:-1] if str[-1]==',' else str
Though it is little bit over work for something like that. I think this statement will help you.
str = 'test1,test2,test3,'
result = ','.join([s for s in str.split(',') if s]) # 'test1,test2,test3'
If you have to remove the last comma (also as the last character?) you can do this via the function removesuffix()
Here is an example:
>>>'hello,'.removesuffix(',')
'hello'
Actually we have to consider the worst case also.
The worst case is,
str= 'test1,test2,test3, ,,,, '
for above code, please use following code,
result = ','.join([s.strip() for s in str.split(',') if s.strip()!=''])
It will work/remove the prefix 'comma' also. For example,
str= ' , ,test1,test2,test3, ,,,, '

Lua: delete specific characters in a string

I have a string that includes all the characters which should be
deleted in a given string. With a nested loop I can iterate through
both strings. But is there a shorter way?
local ignore = "'`'"
function ignoreLetters( c )
local new = ""
for cOrig in string.gmatch(c,".") do
local addChar = 1
for cIgnore in string.gmatch(ignore,".") do
if cOrig == cIgnore then
addChar = 0
break -- no other char possible
end
end
if addChar>0 then new = new..cOrig end
end
return new
end
print(ignoreLetters("'s-Hertogenbosch"))
print(ignoreLetters("'s-Hertogen`bosch"))
The string ignore can also be a table if it makes the code shorter.
You can use string.gsub to replace any occurance of a given string in a string by another string. To delete the unwanted characters, simply replace them with an empty string.
local ignore = "'`'"
function ignoreLetters( c )
return (c:gsub("["..ignore.."]+", ""))
end
print(ignoreLetters("'s-Hertogenbosch"))
print(ignoreLetters("'s-Hertogen`bosch"))
Just be aware that in case you want to ignore magic characters you'll have to escape them in your pattern.
But I guess this will give you a starting point and leave you plenty of own work to perfect.

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'

Removing special characters from a string In a Groovy Script

I am looking to remove special characters from a string using groovy, i'm nearly there but it is removing the white spaces that are already in place which I want to keep. I only want to remove the special characters (and not leave a whitespace). I am running the below on a PostCode L&65$$ OBH
def removespecialpostcodce = PostCode.replaceAll("[^a-zA-Z0-9]+","")
log.info removespecialpostcodce
Currently it returns L65OBH but I am looking for it to return L65 OBH
Can anyone help?
Use below code :
PostCode.replaceAll("[^a-zA-Z0-9 ]+","")
instead of
PostCode.replaceAll("[^a-zA-Z0-9]+","")
To remove all special characters in a String you can use the invert regex character:
String str = "..\\.-._./-^+* ".replaceAll("[^A-Za-z0-1]","");
System.out.println("str: <"+str+">");
output:
str: <>
to keep the spaces in the text add a space in the character set
String str = "..\\.-._./-^+* ".replaceAll("[^A-Za-z0-1 ]","");
System.out.println("str: <"+str+">");
output:
str: < >

Convert underscores to spaces in Matlab string?

So say I have a string with some underscores like hi_there.
Is there a way to auto-convert that string into "hi there"?
(the original string, by the way, is a variable name that I'm converting into a plot title).
Surprising that no-one has yet mentioned strrep:
>> strrep('string_with_underscores', '_', ' ')
ans =
string with underscores
which should be the official way to do a simple string replacements. For such a simple case, regexprep is overkill: yes, they are Swiss-knifes that can do everything possible, but they come with a long manual. String indexing shown by AndreasH only works for replacing single characters, it cannot do this:
>> s = 'string*-*with*-*funny*-*separators';
>> strrep(s, '*-*', ' ')
ans =
string with funny separators
>> s(s=='*-*') = ' '
Error using ==
Matrix dimensions must agree.
As a bonus, it also works for cell-arrays with strings:
>> strrep({'This_is_a','cell_array_with','strings_with','underscores'},'_',' ')
ans =
'This is a' 'cell array with' 'strings with' 'underscores'
Try this Matlab code for a string variable 's'
s(s=='_') = ' ';
If you ever have to do anything more complicated, say doing a replacement of multiple variable length strings,
s(s == '_') = ' ' will be a huge pain. If your replacement needs ever get more complicated consider using regexprep:
>> regexprep({'hi_there', 'hey_there'}, '_', ' ')
ans =
'hi there' 'hey there'
That being said, in your case #AndreasH.'s solution is the most appropriate and regexprep is overkill.
A more interesting question is why you are passing variables around as strings?
regexprep() may be what you're looking for and is a handy function in general.
regexprep('hi_there','_',' ')
Will take the first argument string, and replace instances of the second argument with the third. In this case it replaces all underscores with a space.
In Matlab strings are vectors, so performing simple string manipulations can be achieved using standard operators e.g. replacing _ with whitespace.
text = 'variable_name';
text(text=='_') = ' '; //replace all occurrences of underscore with whitespace
=> text = variable name
I know this was already answered, however, in my case I was looking for a way to correct plot titles so that I could include a filename (which could have underscores). So, I wanted to print them with the underscores NOT displaying with as subscripts. So, using this great info above, and rather than a space, I escaped the subscript in the substitution.
For example:
% Have the user select a file:
[infile inpath]=uigetfile('*.txt','Get some text file');
figure
% this is a problem for filenames with underscores
title(infile)
% this correctly displays filenames with underscores
title(strrep(infile,'_','\_'))

Resources