1

The whole file consists of lines like below.

\"ansText\" : \"11\",
\"boundsX\" : 0,
\"string\" : \"11\"

For any lines starting with title, I would like to remove the character ; from the string after it. Below is an example of expected output

Input:

\"title\" : \"244442424268391(:)7)$(.:$?3.&!&3$83;767:2\",

Output:

\"title\" : \"244442424268391(:)7)$(.:$?3.&!&3$83767:2\",

I know how to set the regular expression to find the expression title by using:

 str0 = re.sub(r'\"title.*',"\"title\" : ",str0) 

But I am not too certain how can I keep the original string but remove only one character.

1
  • 1
    This looks like JSON. Use JSON parser if that is the case. Commented Jan 7, 2016 at 11:08

2 Answers 2

2

You can simply do this use str.replace() and str.startswith() without RegEx like this:

>>> str0 = r'\"title\" : \"244442424268391(:)7)$(.:$?3.&!&3$83;767:2\",'
>>> str0 = str0.replace(';', '') if str0.startswith(r'\"title\" : ') else str0
>>> str0
'\\"title\\" : \\"244442424268391(:)7)$(.:$?3.&!&3$83767:2\\",'
Sign up to request clarification or add additional context in comments.

Comments

1

You could use something like so: (\\"title\\" : \\".+?);(.+?\\") (example here) and replace the string with regex groups number 1 and 2. This expression will look for strings containing \"title\" and a ; character within it and use this information to create two regular expression groups, this given \"title\" : \"244442424268391(:)7)$(.:$?3.&!&3$83;767:2\",, the output would be:;

Group 1: \"title\" : \"244442424268391(:)7)$(.:$?3.&!&3$83
Group 2: 767:2\"

When you combine these 2 strings, you will get the result which you are after.

 str0 = re.sub(r'(\\"title\\" : \\".+?);(.+?\\")',r"\1\2", str0) 

4 Comments

It will fails when there's more ; than one. Right?
@KevinGuan: It should still do what you are after, however the first ; (starting from the left) will not be included in the result.
That's what I meant, I thought OP might want remove all ; from the string if there's more ; in the string instead of just the first one.
@KevinGuan: Yeah I see your point. We'll see whatever the OP decides.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.