Skip to content
Fix Code Error

Python string.replace regular expression

March 13, 2021 by Code Error
Posted By: Anonymous

I have a parameter file of the form:

parameter-name parameter-value

Where the parameters may be in any order but there is only one parameter per line. I want to replace one parameter’s parameter-value with a new value.

I am using a line replace function posted previously to replace the line which uses Python’s string.replace(pattern, sub). The regular expression that I’m using works for instance in vim but doesn’t appear to work in string.replace().

Here is the regular expression that I’m using:

line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn))

Where "interfaceOpDataFile" is the parameter name that I’m replacing (/i for case-insensitive) and the new parameter value is the contents of the fileIn variable.

Is there a way to get Python to recognize this regular expression or else is there another way to accomplish this task?

Solution

str.replace() v2|v3 does not recognize regular expressions.

To perform a substitution using a regular expression, use re.sub() v2|v3.

For example:

import re

line = re.sub(
           r"(?i)^.*interfaceOpDataFile.*$", 
           "interfaceOpDataFile %s" % fileIn, 
           line
       )

In a loop, it would be better to compile the regular expression first:

import re

regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
    line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
    # do something with the updated line
Answered By: Anonymous

Related Articles

  • Design DFA accepting binary strings divisible by a…
  • Easy interview question got harder: given numbers…
  • Circle line-segment collision detection algorithm?
  • What is your most productive shortcut with Vim?
  • How do I install a plugin for vim?
  • Unable to see color in vim after upgrade
  • Examples of GoF Design Patterns in Java's core libraries
  • Having trouble with my nav bar/header, It used to…
  • Reversing a string in C
  • Adding Dynamic Input Fields With VueJs
  • What are the undocumented features and limitations…
  • What is the difference between MacVim and regular Vim?
  • Can't install via pip because of egg_info error
  • Best way to replace multiple characters in a string?
  • Azure CLI - az deployment group create -…
  • laravel vuejs/axios put request Formdata is empty
  • Reference - What does this regex mean?
  • Adding a UserCreationForm to html in Django
  • Form field border-radius is not working only on the…
  • javascript .replace and .trim not working in vuejs
  • What's the difference between eval, exec, and compile?
  • How to paste yanked text into the Vim command line
  • Azure Availability Zone ARM Config
  • Django - update inline formset not updating
  • How to use Regular Expressions (Regex) in Microsoft…
  • Why the value of input file missing when I input the…
  • How to make vim paste from (and copy to) system's clipboard?
  • Start redis-server with config file
  • Git submodule head 'reference is not a tree' error
  • Vim auto-indenting xml strangely
  • Why does this regular expression not work in Vim…
  • How can I enable Vim syntax highlighting for…
  • How to dynamically add and remove form fields in Angular 2
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Complex nesting of partials and templates
  • How to copy files inside a local virtual machine or…
  • How to submit Polymer forms to PHP and display response
  • How can I pass modelformset_factory validation in Django?
  • How to display gpg key details without importing it?
  • Smart way to truncate long strings
  • How do you match strings in custom Instruments…
  • Difference between / and /* in servlet mapping url pattern
  • How to select all and copy in vim?
  • Using Vim's tabs like buffers
  • How to use Servlets and Ajax?
  • How can I programmaticaly copy text from notepad and…
  • How do I run a terminal inside of Vim?
  • What are the benefits of learning Vim?
  • How to copy to clipboard in Vim?
  • Understanding constraints in agrep fuzzy matching in R
  • How to use vim in the terminal?
  • Are dictionaries ordered in Python 3.6+?
  • Ember data parent / child models and json
  • How to find out client ID of component for ajax…
  • shell script. how to extract string using regular…
  • TypeError: 'undefined' is not an object
  • Angular 4 HttpClient Query Parameters
  • How do I merge two dictionaries in a single…
  • commandButton/commandLink/ajax action/listener…
  • Why is Ember throwing "Uncaught Error: Assertion…
  • What's wrong with overridable method calls in constructors?
  • Understanding PrimeFaces process/update and JSF…
  • How do I change tab size in Vim?
  • how to make column bool data to be true with the…
  • Add virtual network to existing Event hub namespace
  • Add Bootstrap Glyphicon to Input Box
  • How to set default vim colorscheme
  • ORA-01008: not all variables bound. They are bound
  • How to parse deserialized object back into arrays?
  • ComboBox.SelectedItem giving Null value
  • How does PHP 'foreach' actually work?
  • How to update Python?
  • java.util.regex - importance of Pattern.compile()?
  • How to get WooCommerce order details
  • Vuejs Property or method is not defined on the…
  • Modifying SIR model to include stochasticity
  • A shortcut to fire up vim on the text typed on the…
  • Improve INSERT-per-second performance of SQLite
  • Triggering text area by clicking related select/checkbox
  • Changing Vim indentation behavior by file type
  • The definitive guide to form-based website authentication
  • Java SimpleDateFormat for time zone with a colon separator?
  • How to calculate an angle from three points?
  • How would I be able to multiple select and pass data…
  • So can't use weasyprint what is the best thing to do?
  • Applying design patterns whilst collaborating with…
  • How do I install PIL/Pillow for Python 3.6?
  • Using git commit -a with vim
  • setTimeout function not working : javascript
  • How can I parse a CSV string with JavaScript, which…
  • An Authentication object was not found in the…
  • How can I use numpy.correlate to do autocorrelation?
  • How do I create a URL shortener?
  • Vue Router beforeRouteLeave doesn't stop subcomponents
  • Java Regex Capturing Groups
  • How to use java.net.URLConnection to fire and handle…
  • SQL Insert Query Using C#
  • Creating a singleton in Python
  • Add Keypair to existing EC2 instance
  • Java - How Can I Write My ArrayList to a file, and…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

Next Post:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error