Reputation:
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?
Upvotes: 1
Views: 282
Reputation: 42184
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'
Upvotes: 1
Reputation: 21
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
Upvotes: 2