0

Can't get the code to work, following code should replace what ever is after = and before "

user = "/silent test=de";

#!/usr/bin/python
import re
import fileinput

langids = ["de","uk","us","dk"]

for lang in langids:
 for line in fileinput.FileInput("C:\Users\HS\Desktop\sps_r2850\Test.txt",inplace=1):
    if re.match(".*user = \"[a-zA-Z/_= ]*\";.*", line):
        line = ("user = \"/silent test=_%s\";\n" % lang)
    print line,
3
  • 1
    First, better use raw strings when dealing with strings that contain backslashes (like Windows file paths and regexes). Then, how is your code "not working"? Does it match the wrong texts? Doesn't it match anything? Doesn't it replace the right parts? Commented Nov 15, 2012 at 8:27
  • 1. where exactly is it replacing anything? you arent even using re.sub Commented Nov 15, 2012 at 8:31
  • Hey i'm a noob regex in python, however this code doesn't do anything. If i create a line in TEST.txt : 'user = "/silent test=tat";' then nothing happen, after i have run the code. Commented Nov 15, 2012 at 8:41

1 Answer 1

3

Change the language using re.sub:

import re

# no value set (or any doesn't matter)
line='user = "/silent test=";'

# values to insert 
langids = ["de","uk","us","dk"]

for lang in langids: 
     print re.sub('(.*=)(.*)(".*)',r'\1'+lang+r'\3',line)

# output
>>> user = "/silent test=de";
>>> user = "/silent test=uk";
>>> user = "/silent test=us";
>>> user = "/silent test=dk";
Sign up to request clarification or add additional context in comments.

4 Comments

Can't use this, since "de" is a random ID. So i have to use regex to find the ID, and i need to change that random ID with my own ID.
Great thx, but this just overwrite the lang. Can you do so it don't overwrite, but instead pick the next lang after a loop?
On that basis, please edit the question to include example input and expected output, as it is not clear what is required.
@user1823753 nothing is overwritten, the output is displayed (i.e print) it does go through all the languages in the loop? I not sure what you asking for?

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.