Hell Lord
Hell Lord

Reputation: 37

Regular Expression to remove lines from a file

I have a *.txt file which have unnecessary strings which look along the lines of:

------------------------[ # ]-------------------------

The problem persists that the # is any integer. I confused and are looking for a regular expression which finds the above string.

Any help would be greatly appreciated.

Upvotes: 0

Views: 175

Answers (2)

bluegman991
bluegman991

Reputation: 727

You best bet would be regular expression.

//read your text file into a variable named $filecont
/\-+\[\s\d+\s\]\-+(?:\r?\n|$)/g
//write the contents of $filecont to your file

The above will remove any lines that begin with 1 or more dashes followed by an opening bracket, followed by space, followed by 1 or more numbers, followed by space, followed by a closing bracket followed by 1 or more dashes.

Using the above regular expression will convert the following data

----------------[ 56 ]---------------------
Line of text
------------[ 929 ]--------------------
Another line of text
-----------------------------[ 1 ]----------
Last line of text

to

Line of text
Another line of text
Last line of text

Upvotes: 3

nderjung
nderjung

Reputation: 1617

You can use the following regular expression:

/((?:-+)\[\s\d+\s\](?:-+))/igs

The expression will captures expressions with all numbers, from 0 to infinity.

Finally, I recommend using this tool for new comers to the regular expression world, it helps visualise and understand how the regular expression works with your content.

Upvotes: 1

Related Questions