Remove part of string (regular expressions) - groovy

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'

Related

re.sub replacing string using original sub-string

I have a text file. I would like to remove all decimal points and their trailing numbers, unless text is preceding.
e.g 12.29,14.6,8967.334 should be replaced with 12,14,8967
e.g happypants2.3#email.com should not be modified.
My code is:
import re
txt1 = "9.9,8.8,22.2,88.7,morris1.43#email.com,chat22.3#email.com,123.6,6.54"
txt1 = re.sub(r',\d+[.]\d+', r'\d+',txt1)
print(txt1)
unless there is an easier way of completing this, how do I modify r'\d+' so it just returns the number without a decimal place?
You need to make use of groups in your regex. You put the digits before the '.' into parentheses, and then you can use '\1' to refer to them later:
txt1 = re.sub(r',(\d+)[.]\d+', r',\1',txt1)
Note that in your attempted replacement code you forgot to replace the comma, so your numbers would have been glommed together. This still isn't perfect though; the first number, since it doesn't begin with a comma, isn't processed.
Instead of checking for a comma, the better way is to check word boundaries, which can be done using \b. So the solution is:
import re
txt1 = "9.9,8.8,22.2,88.7,morris1.43#email.com,chat22.3#email.com,123.6,6.54"
txt1 = re.sub(r'\b(\d+)[.]\d+\b', r'\1',txt1)
print(txt1)
Considering these are the only two types of string that is present in your file, you can explicitly check for these conditions.
This may not be an efficient way, but what I have done is split the str and check if the string contains #email.com. If thats true, I am just appending to a new list. For your 1st condition to satisfy, we can convert the str to int which will eliminate the decimal points.
If you want everything back to a str variable, you can use .join().
Code:
txt1 = "9.9,8.8,22.2,88.7,morris1.43#email.com,chat22.3#email.com,123.6,6.54"
txt_list = []
for i in (txt1.split(',')):
if '#email.com' in i:
txt_list.append(i)
else:
txt_list.append(str(int(float(i))))
txt_new = ",".join(txt_list)
txt_new
Output:
'9,8,22,88,morris1.43#email.com,chat22.3#email.com,123,6'

Convert a string to a set without splitting the characters

I have a quick question: a='Tom', a type of str. I want to make it into a set with one item. If I use the command b = set(a), I got a set with 3 items in it, which is set(['m',''T','o']). I want set(['Tom']). How could I get it? Thanks.
The set builtin makes sets out of iterables. Iterating over a string yields each character one-by-one, so wrap the string in some other iterable:
set(['Tom'])
set(('Tom',))
If you're used to the mathematical notation for sets, you can just use curly braces (don't get it confused with the notation for dictionaries):
{'Tom'}
{'Tom', 'Bob'}
The resulting sets are equivalent
>>> {'Tom'} == set(['Tom']) == set(('Tom',))
True
set(['Tom'])
You just answered your own question (give list, instead of string).
Like this:
a = "Tom"
b = set([a])

String manipulation in Lua: Swap characters in a string

I'm trying to do a function in Lua that swaps the characters in a string.
Can somebody help me ?
Here is an example:
Input = "This LIBRARY should work with any string!"
Result = "htsil biaryrs ohlu dowkrw ti hna ytsirgn!"
Note: The space is also swapped
Thank You Very Much :)
The simplest and clearest solution is this:
Result = Input:gsub("(.)(.)","%2%1")
This should do it:
input = "This LIBRARY should work with any string!"
function swapAlternateChars(str)
local t={}
-- Iterate through the string two at a time
for i=1,#str,2 do
first = str:sub(i,i)
second = str:sub(i+1,i+1)
t[i] = second
t[i+1] = first
end
return table.concat(t)
end
print(input)
print(swapAlternateChars(input))
Prints:
This LIBRARY should work with any string!
hTsiL BIARYRs ohlu dowkrw ti hna ytsirgn!
If you need the output as lower case you could always end it with:
output = swapAlternateChars(input)
print(string.lower(output))
Note, in this example, I'm not actually editing the string itself, since strings in Lua are immutable. Here's a read: Modifying a character in a string in Lua
I've used a table to avoid overhead from concatenating to a string because each concatenation may allocate a new string in memory.

Multiline string literal in Matlab?

Is there a multiline string literal syntax in Matlab or is it necessary to concatenate multiple lines?
I found the verbatim package, but it only works in an m-file or function and not interactively within editor cells.
EDIT: I am particularly after readbility and ease of modifying the literal in the code (imagine it contains indented blocks of different levels) - it is easy to make multiline strings, but I am looking for the most convenient sytax for doing that.
So far I have
t = {...
'abc'...
'def'};
t = cellfun(#(x) [x sprintf('\n')],t,'Unif',false);
t = horzcat(t{:});
which gives size(t) = 1 8, but is obviously a bit of a mess.
EDIT 2: Basically verbatim does what I want except it doesn't work in Editor cells, but maybe my best bet is to update it so it does. I think it should be possible to get current open file and cursor position from the java interface to the Editor. The problem would be if there were multiple verbatim calls in the same cell how would you distinguish between them.
I'd go for:
multiline = sprintf([ ...
'Line 1\n'...
'Line 2\n'...
]);
Matlab is an oddball in that escape processing in strings is a function of the printf family of functions instead of the string literal syntax. And no multiline literals. Oh well.
I've ended up doing two things. First, make CR() and LF() functions that just return processed \r and \n respectively, so you can use them as pseudo-literals in your code. I prefer doing this way rather than sending entire strings through sprintf(), because there might be other backslashes in there you didn't want processed as escape sequences (e.g. if some of your strings came from function arguments or input read from elsewhere).
function out = CR()
out = char(13); % # sprintf('\r')
function out = LF()
out = char(10); % # sprintf('\n');
Second, make a join(glue, strs) function that works like Perl's join or the cellfun/horzcat code in your example, but without the final trailing separator.
function out = join(glue, strs)
strs = strs(:)';
strs(2,:) = {glue};
strs = strs(:)';
strs(end) = [];
out = cat(2, strs{:});
And then use it with cell literals like you do.
str = join(LF, {
'abc'
'defghi'
'jklm'
});
You don't need the "..." ellipses in cell literals like this; omitting them does a vertical vector construction, and it's fine if the rows have different lengths of char strings because they're each getting stuck inside a cell. That alone should save you some typing.
Bit of an old thread but I got this
multiline = join([
"Line 1"
"Line 2"
], newline)
I think if makes things pretty easy but obviously it depends on what one is looking for :)

Remove Characters from the end of a String Scala

What is the simplest method to remove the last character from the end of a String in Scala?
I find Rubys String class has some very useful methods like chop. I would have used "oddoneoutz".headOption in Scala, but it is depreciated. I don't want to get into the overly complex:
string.slice(0, string.length - 1)
Please someone tell me there is a nice simple method like chop for something this common.
How about using dropRight, which works in 2.8:-
"abc!".dropRight(1)
Which produces "abc"
string.init // padding for the minimum 15 characters
val str = "Hello world!"
str take (str.length - 1) mkString
If you want the most efficient solution than just use:
str.substring(0, str.length - 1)
string.reverse.substring(1).reverse
That's basically chop, right? If you're longing for a chop method, why not write your own StringUtils library and include it in your projects until you find a suitable, more generic replacement?
Hey, look, it's in commons.
Apache Commons StringUtils.
If you want just to remove the last character use .dropRight(1). Alternatively, if you want to remove a specific ending character you may want to use a match pattern as
val s: String = "hello!"
val sClean: String = s.takeRight(1) match {
case "!" => s.dropRight(1)
case _ => s
}

Resources