Thursday, July 19, 2007

Regex with Named Groups

Suppose you want to remove a middle name from name you can use “replace” method in your favorite language/editor in this way..
You Regulare Expression: (?(\w+))\s*(?(\w+))\s*(?(\w+))\s*

Replace with: ${ FirstName } ${ LastName }

Some days before when I needed help about this, googling didn’t help much. If you come across any good link about this, don’t forget to put a comment here.

(This may be a bad example but I am using it just for simplicity and the sole objective of this blog is to understand 'named group' or 'variable')

[Updates]
Tutorial Link:
http://www.regular-expressions.info/named.html

2 comments:

Anonymous said...

With awk, in fact, it's quite easy:

cat fullnames | awk '{ print $1 " " $3 }' >> newnames

The file fullnames contains the names in the format "FirstName MiddleName LastName" and the file "newnames" will contain just the First Name and the Last Name

Yogee said...

Yes, awk stands apart for processing like this. But if you go little complex, you will choose regular expression as an option in awk itself and that too without compromising on decency of the program.