By alvas


2011-04-14 03:59:21 8 Comments

I need some help on declaring a regex. My inputs are like the following:

this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
and there are many other lines in the txt files
with<[3> such tags </[3>

The required output is:

this is a paragraph with in between and then there are cases ... where the number ranges from 1-100. 
and there are many other lines in the txt files
with such tags

I've tried this:

#!/usr/bin/python
import os, sys, re, glob
for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
    for line in reader: 
        line2 = line.replace('<[1> ', '')
        line = line2.replace('</[1> ', '')
        line2 = line.replace('<[1>', '')
        line = line2.replace('</[1>', '')

        print line

I've also tried this (but it seems like I'm using the wrong regex syntax):

    line2 = line.replace('<[*> ', '')
    line = line2.replace('</[*> ', '')
    line2 = line.replace('<[*>', '')
    line = line2.replace('</[*>', '')

I dont want to hard-code the replace from 1 to 99 . . .

7 comments

@Abena Saulka 2019-01-24 21:15:31

import os, sys, re, glob

pattern = re.compile(r"\<\[\d\>")
replacementStringMatchesPattern = "<[1>"

for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
   for line in reader: 
      retline =  pattern.sub(replacementStringMatchesPattern, "", line)         
      sys.stdout.write(retline)
      print (retline)

@Lorenzo Persichetti 2013-06-27 08:28:31

I would go like this (regex explained in comments):

import re

# If you need to use the regex more than once it is suggested to compile it.
pattern = re.compile(r"</{0,}\[\d+>")

# <\/{0,}\[\d+>
# 
# Match the character “<” literally «<»
# Match the character “/” literally «\/{0,}»
#    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «{0,}»
# Match the character “[” literally «\[»
# Match a single digit 0..9 «\d+»
#    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “>” literally «>»

subject = """this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. 
and there are many other lines in the txt files
with<[3> such tags </[3>"""

result = pattern.sub("", subject)

print(result)

If you want to learn more about regex I recomend to read Regular Expressions Cookbook by Jan Goyvaerts and Steven Levithan.

@HamZa 2013-06-27 10:39:50

You could simply use * instead of {0,}

@winklerrr 2017-08-17 14:07:14

From the python docs: {0,} is the same as *, {1,} is equivalent to +, and {0,1} is the same as ?. It’s better to use *, +, or ? when you can, simply because they’re shorter and easier to read.

@Zac 2013-05-16 10:42:21

replace method of string objects does not accept regular expressions but only fixed strings (see documentation: http://docs.python.org/2/library/stdtypes.html#str.replace).

You have to use re module:

import re
newline= re.sub("<\/?\[[0-9]+>", "", line)

@winklerrr 2017-08-17 14:05:29

You should use \d+ instead of [0-9]+

@Ezequiel Marquez 2013-05-14 16:13:42

The easiest way

import re

txt='this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>.  and there are many other lines in the txt files with<[3> such tags </[3>'

out = re.sub("(<[^>]+>)", '', txt)
print out

@winklerrr 2017-08-17 14:12:12

Are the parentheses really necessary? Wouldn't that be the same regex: <[^>]+>? By the way: I think your regex would match too much (e.g. something like <html>)

@ridgerunner 2011-04-14 04:12:17

This tested snippet should do it:

import re
line = re.sub(r"</?\[\d+>", "", line)

Edit: Here's a commented version explaining how it works:

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line)

Regexes are fun! But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: "metacharacters" which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!

@alvas 2011-04-14 06:39:57

yep it works!! thanks but can you explain the regex in brief?

@pcurry 2013-05-14 05:05:33

Also don't neglect The Book on Regular Expressions - Mastering Regular Expressions, by Jeffrey Friedl

@kurumi 2011-04-14 04:06:17

don't have to use regular expression (for your sample string)

>>> s
'this is a paragraph with<[1> in between</[1> and then there are cases ... where the<[99> number ranges from 1-100</[99>. \nand there are many other lines in the txt files\nwith<[3> such tags </[3>\n'

>>> for w in s.split(">"):
...   if "<" in w:
...      print w.split("<")[0]
...
this is a paragraph with
 in between
 and then there are cases ... where the
 number ranges from 1-100
.
and there are many other lines in the txt files
with
 such tags

@Ignacio Vazquez-Abrams 2011-04-14 04:00:53

str.replace() does fixed replacements. Use re.sub() instead.

@user684934 2011-04-14 04:05:11

Also worth noting that your pattern should look something like "</{0-1}\d{1-2}>" or whatever variant of regexp notation python uses.

@avi 2015-07-03 11:35:14

What does fixed replacements mean?

@Gunay Anach 2017-07-11 08:48:54

@avi Probably he meant fixed word replacement rather partial word locating through regex.

@vstepaniuk 2019-07-31 11:54:38

fixed (literal, constant) strings

Related Questions

Sponsored Content

90 Answered Questions

[SOLVED] How to validate an email address in JavaScript

61 Answered Questions

[SOLVED] How to replace all occurrences of a string?

73 Answered Questions

85 Answered Questions

[SOLVED] How do I make the first letter of a string uppercase in JavaScript?

11 Answered Questions

[SOLVED] How do I get a substring of a string in Python?

42 Answered Questions

[SOLVED] How do I merge two dictionaries in a single expression?

38 Answered Questions

[SOLVED] How do I check whether a file exists without exceptions?

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

4 Answered Questions

76 Answered Questions

[SOLVED] How do I iterate over the words of a string?

  • 2008-10-25 08:58:21
  • Ashwin Nanjappa
  • 2151463 View
  • 2923 Score
  • 76 Answer
  • Tags:   c++ string split

Sponsored Content