Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing first appearance of word from a string?

Tags:

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!

like image 802
zhuyxn Avatar asked May 18 '12 07:05

zhuyxn


People also ask

How do I remove the first word from a string?

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!

How do I remove the first occurrence of a character from a string?

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.

How do I remove the first word from a string in Python?

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.

How do you remove the first word from a sentence in Java?

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.


1 Answers

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: ' 
like image 71
Josiah Avatar answered Oct 18 '22 18:10

Josiah