Dean Allard
Dean Allard

Reputation: 57

Looking for a regular expression solution

I'm looking for a regular expression that matches the first two specific fields (variable strings written in Perl). In a file a line without a comment # starts with any character, length unspecific followed by a whitespace and another nonspecific length string followed by a whitespace: name info data1 data2 data3.

The following works for matching the second field only but I want the first two fields to match exactly: /^[^#].*\s$INFO\s/ where $INFO="info". I tried variations of the above to no avail. My first attempt was this: /^[^#]$NAME\s$INFO\s/ which seemed logical to me if $NAME="name" for the above record.

Upvotes: 0

Views: 100

Answers (2)

AD7six
AD7six

Reputation: 66170

My first attempt was this: /^[^#]$NAME\s$INFO\s/

This won't work because (implied from the question) the character before $NAME is either # or nothing. As such you just need to remove that first [^#]:

/^$NAME\s$INFO\s/

Which will match the string:

"$NAME $INFO <whatever or nothing>"

Upvotes: 2

d&#39;alar&#39;cop
d&#39;alar&#39;cop

Reputation: 2365

Although I'm not a regex expert, this may work (I also am not clear on the precise details of the question so I made some assumptions):

'$NAME=name #$INFO=info $DATA=data1 data2 data3'.replace(/#[\S]+/g,'').match(/\$[\S]+/g);

This returns an array. The first 2 elements are the 'fields' i.e. [0]='$NAME=name' AND [1]='$DATA=data1'

Hope that helps at all. And apologies to the gods for my regex.

Upvotes: 1

Related Questions