I am looking for advice on extracting a section of a string that always appears as first instance data between brackets using perl and regex and assigns this value to a variable.
Here is the exact situation. I use perl and regex to extract the course identifier from the university directory and assign it to a variable. Please note the following:
- BIO-2109-01 (12345) Introduction to Biology
- CHM-3501-F2-01 (54321) Introduction to Chemistry
- IDS-3250-01 (98765) US History (1860-2000)
- SPN-1234-02-F1 (45678) History of Spain (1900-2010)
A typical format is [course name] [[course identifier]] [course name]
My goal is to create a script that can take each record, one at a time, assign it to a variable, and then use a regular expression to extract only the course identifier and assign the CourseID variable only to the variable.
My approach was to use search and replace to replace anything that doesn't match this with ``, and then save the remaining (course identifier) variable. Here are some examples of what I have tried:
$string = "BIO-2109-01 (12345) Introduction to Biology";
($courseID = $string) =~ s/[^\d\d\d\d\d]//g;
print $courseID;
Result: 21090112345 --- print the name of the course section and the course identifier
$string = "BIO-2109-01 (12345) Introduction to Biology";
$($courseID = $string) =~ s/[^\b\(\d{5}\)]\b//g;
print $courseID;
Result: 210901 (12345) --- print the name of the course section, parens and courseID
So I was not lucky with the search and replace - however, I found this nugget:
\(([^\)]+)\)
http://regexr.com/, parens. , , , , (abc).
, - :
$string = "BIO-2109-01 (12345) Introduction to Biology";
($courseID = $string) =~ [magicRegex_goes_here];
print courseID;
12345
, :
$string = IDS-3250-01 (98765) History of US (1860-2000)
($courseID = $string) =~ [magicRegex_goes_here];
print courseID;
98765
. , , . , , , .
UPDATE
use warnings 'all';
use strict;
use feature 'say';
my $file = './data/enrollment.csv';
my $course = "";
my @arrayCourses = "";
my $i = "";
my $courseID = "";
my $userName = "";
my $action = "add,";
my $permission = "teacher,";
my $stringToPrint = "";
my $n = "\n";
my $c = ",";
print "Enter the username \n";
chomp($userName = <STDIN>);
print "\n";
print "Enter course name and press enter. Enter 'x' to end. \n";
while ($course ne 'x') {
chomp($course = <STDIN>);
if ($course ne "x") {
if (($courseID) = ($course =~ /[^(]+\(([^)]+)\)/) ) {
push @arrayCourses, $courseID;
}
else {
print "Cannot process last entry check it";
}
}
else {
last;
}
}
shift @arrayCourses;
open(my $fh,'>', $file);
for $i (@arrayCourses)
{
$stringToPrint= join "", $action, $permission, $i, $c, $userName, $n ;
print $fh $stringToPrint;
}
close $fh;
! ! @PerlDuck @zdim