Simple regex problem (I think so anyway)

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
AlanG
Forum Contributor
Posts: 136
Joined: Wed Jun 10, 2009 1:03 am

Simple regex problem (I think so anyway)

Post by AlanG »

I'm so hopeless with regex. Was hoping someone could give me a helping hand. :)

I've got a file with various strings on each line. I want to add a new line character after each of the following patterns. (nxt is a literal string and N is an integer)

Code: Select all

 
Any number of varying characters-NNNNN
Any number of varying characters-NNNNN-NN
nxt
 
Any ideas? :) And thanks for any suggestions.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Simple regex problem (I think so anyway)

Post by AbraCadaver »

Just quickly tested:

Code: Select all

$file = preg_replace('/((.+-[\d]{5}(-[\d]{2})?)|(nxt))/', "$1\n", $file);
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
AlanG
Forum Contributor
Posts: 136
Joined: Wed Jun 10, 2009 1:03 am

Re: Simple regex problem (I think so anyway)

Post by AlanG »

AbraCadaver wrote:Just quickly tested:

Code: Select all

$file = preg_replace('/((.+-[\d]{5}(-[\d]{2})?)|(nxt))/', "$1\n", $file);
Excellent! Thank you very much. Tested it and it works perfectly. :)
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: Simple regex problem (I think so anyway)

Post by ridgerunner »

AbraCadaver wrote:Just quickly tested:

Code: Select all

$file = preg_replace('/((.+-[\d]{5}(-[\d]{2})?)|(nxt))/', "$1\n", $file);
This can be simplified a bit. You don't need to enclose the \d within a character class. Also, the two alternatives don't need to be in parentheses...

Code: Select all

$file = preg_replace('/(.+-\d{5}(-\d{2})?|nxt)/', "$1\n", $file);
Post Reply