I'm not familiar with regex, and it would be great if someone giving a solution using regex could explain their syntax so I can apply it to future situations.
I have a string (ie. 'Description: Mary had a little lamb'
), and I would like to remove 'Description: '
such that the string would read 'Mary had a little lamb,'
but only the first instance, such that if the string was 'Description: Description'
, the new string would be 'Description.'
Any ideas? Thanks!
To remove the first word from a string, call the indexOf() method to get the index of the first space in the string. Then use the substring() method to get a portion of the string, with the first word removed. Copied!
Logic to remove first occurrence of a character in stringInput character to remove from user, store it in some variable say toRemove. Find first occurrence of the given character toRemove in str. From the first occurrence of given character in string, shift next characters one place to its left.
Method #1: Using split() Method This task can be performed using the split function which performs a split of words and separates the first word of string with the entire words.
The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.
Python's str.replace has a max replace argument. So, in your case, do this:
>>>mystring = "Description: Mary had a little lamb Description: " >>>print mystring.replace("Description: ","",1) "Mary had a little lamb Description: "
Using regex is basically exactly the same. First, get your regex:
"Description: "
Since Python is pretty nice about regexes, it's just the string you want to remove in this case. With that, you want to use it in re.sub, which also has a count variable:
>>>import re >>>re.sub("Description: ","",mystring,count=1) 'Mary had a little lamb Description: '
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With