in reply to Re: RegEx question
in thread RegEx question

Thanks for you answers,

Unfortunately, the text can contain whitespace, several words, sometimes comma separated.

The second example would not work because I chose a misleading example. The labels are not necessarily named Label1, Label2, ... LabelN. They can be different words. A better example would be:

"some text .... Programming Languages: C++, Java Author: John Date Cre +ated: 20004-01-05 10:23 ....."

In this case, I would need to extract the string: "C++, Java".

Again, thanks for taking the time to look at this.

Marius

Replies are listed 'Best First'.
Re^3: RegEx question
by davido (Cardinal) on Oct 01, 2006 at 05:24 UTC

    Well then, you've got a problem, but I'm going to propose a solution. First, I'll try to explain the problem.

    If one label is "Programming Languages:", another label is "Author:", and another is "Date Created:", you clearly cannot count on the labels not having whitespace. And if your data fields are "C++, Java", "John", "2004-01-05 10:23...", you clearly cannot count on your data fields not containing whitespace. Your fields aren't of fixed width either. And your delimiter (the colon) appears mid-record, so it's more of an anchor than a delimiter, which doesn't help tremendously. What that leaves you with is this: No good way of determining where a data field ends, and where a new label starts. ......unless, of course.... unless you're lucky enough to know all the possible labels.

    Maybe you could instead skim for known labels. That would be helpful. For example, if you know that the only labels in the text are "Programming Languages", "Author", and "Date Created", you could compose your regular expression like this:

    my $labels = qr/Programming Languages|Author|Date Created/; my $re = qr/($labels):(.+?)(?=$labels|$)/; while( my( $label, $data ) = $text =~ m/$re/g ) { print "Label: $label\tData: $data\n"; }

    This will capture the known label into $label on each iteration, and then the field following the label into $data. Each match stops as soon as the lookahead assertion finds the next known label, or the end of the string.


    Dave

Re^3: RegEx question
by GrandFather (Saint) on Oct 01, 2006 at 05:29 UTC

    Are you getting the original data one entry at a time, or are several entries munged together?

    The solution is simple if you get the data one entry per line and there is no more than one word for the second label ('Author' in your example). A slight modification of McDarren's sample is what you are after:

    use strict; use warnings; my $line = "some text Programming Languages: C++, Java Author: John D +ate Created: 20004-01-05 10:23"; my ($text) = $line =~ / ^[^:]* # Skip everything from the start of line until the first : :\s+ # Skip the : and any trailing white space ( # Capture (?: # Group, but don't capture (?! # look ahead an fail to match if given pattern fou +nd \s+\w+: # Pattern to fail on - space word : ). # Capture a character if the look ahead didn't fai +l )* # Do it as many times as possible ) # Close the capture /x; # x flag ignores most white space and allows comments print $text;

    Prints:

    C++, Java

    DWIM is Perl's answer to Gödel
Re^3: RegEx question
by McDarren (Abbot) on Oct 01, 2006 at 05:05 UTC
    I'm thinking that a good approach to this may be to split your data into a hash, but it's difficult to be sure about that given the data that you've shown.

    Could you post 3-4 full lines of the actual data that you are working with? (edit anything that may be sensitive, of course).

    Update: Just looked at this again. Will the word "Author" always follow the text that you need to extract?

    If yes, then you could probably just do:

    /:\s(.*?)Author:/

    But again, difficult to say for certain without seeing a few more lines of data and having the requirements clarified a bit.

      Thanks guys,

      I appologize for not explaining this better.

      Here's what actual data looks like:

      "OSTG ThinkGeek Slashdot ITMJ Linux.com NewsForge freshmeat Newsletter +s PriceGrabber Jobs Broadband ; SourceForge.net Search Advanced Log I +n - Create Account SF.net Home About Supporters Site;News Create;Proj +ect Subscribe Newsletter Compile;Farm Projects Software;Map Create;Pr +oject New;Releases Top;Projects New;Projects Help;Wanted My Page Summ +ary Projects Tracker Tasks Donations Preferences Help Get;Support Doc +umentation Site;Updates Priority;Support Site;Status ; ; Provide feed +back on this page ; Recently changed page ; Site Status SF.net Projec +ts Phatsoft TMR Summary ; ; Phatsoft TMR ; Donate to project ; Stats +- Activity: 82.51% RSS Advanced Summary Admin Home;Page Forums Tracke +r Bugs Support;Requests Patches Feature;Requests Mail Screenshots New +s Files ; ; TMR is a lightweight reminder utility that works with Win +dows on scheduled tasks. Like the yellow stickies, the program pops u +p with a message at a set time, shuts down or restarts your computer, + opens a file, or starts an application. ; ; Download Phatsoft TMR ; +; ; Project Admins : lucamartinetti Operating System : All 32-bit MS +Windows (95/98/NT/2000/XP) License : GNU General Public License (GPL) + Category : (None Listed) Need Support? : See the support instruction +s provided by this project ; ; Latest News ; ; 1.3.0.2 - BIG FIXES - +Update reccomended! ; 2003-09-22 TMR on TechTV's 'Call for Help' ; 20 +03-03-17 News archive » ; ; Public Areas ; ; Bugs : (11 open / +22 total) Bug Tracking System Support Requests : (12 open / 17 total) + Tech Support Tracking System Patches : (0 open / 0 total) Patch Trac +king System Feature Requests : (18 open / 26 total) Feature Request T +racking System Public Forums : (11 messages in 2 forums) Mailing List +s : (1 total) ; ; Project Details ; ; Project Admins : lucamartinetti + Developers : 2 Development Status : 5 - Production/Stable Intended A +udience : End Users/Desktop License : GNU General Public License (GPL +) Operating System : All 32-bit MS Windows (95/98/NT/2000/XP) Program +ming Language : C++ Translations : English User Interface : Win32 (MS + Windows) Project UNIX name : tmr Registered : 2003-01-25 03:25 Activ +ity Percentile (last week) : 82.51 View project activity statistics V +iew list of RSS feeds available for this project ; ; ; About SourceFo +rge.net About OSTG Privacy Statement Terms of Use Advertise Get Suppo +rt RSS Powered by the SourceForge® collaborative development envi +ronment from VA Software ©Copyright 2006 - OSTG Open Source Tech +nology Group, All Rights Reserved"

      This is basically, a SourceForge project summary page where I strip all HTML and end up with this text. I want to be able to extract as many project attributes as possible, such as: Programming Language, Translations, Developers, Activity, Topic and so on.

      Now here's where the problem comes, some projects will have some attributes and other projects won't have them. For example, not all projects have the "User Interface Attribute" or the "Donors" attribute, etc... This basically makes for not being able to depend on the order in which these attributes appear in the text.

      So because the order is inconsistent from a project to another I can't do something like:

      if ( $txt =~ /Programming Language : (.*) License :/i ) { $result = $1; }

      and would have to rely on something else. Is there any way to extract the pattern that matches a label and have something like:

      if ( $txt =~ /Programming Language : (.*) $LABEL_PATTERN/i ) { $result = $1; }

      ? This way I can make a list of all possible labels and look for each one individually

Re^3: RegEx question
by shmem (Chancellor) on Oct 01, 2006 at 08:42 UTC
    A dataset, please. Provide a complete dataset that shows your problem. And a piece of code from your keyboard to see where you're stuck.

    I'ts annoying to find out that a given solution doesn't fit because the problem wasn't exposed clearly in the first place.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}