vendredi 31 juillet 2015

Hash and values

I came across this Ruby script:

frequency = Hash.new(0)
...
...
file.read.downcase.scan(/\b[a-z]{4,20}\b/){|word| frequency[word] =
frequency[word]+1}

The point I couldn't understand is frequency[word] = frequency[word]+1

Wouldn't frequency[word] give me the word matched? How can we add it to 1?

parsing URL in newspaper website

I have many urls from the same newspaper, each url has a depository for each writer.

For example:

  1. http://ift.tt/1VSGZfJ
  2. http://ift.tt/1JWQ5PI
  3. http://ift.tt/1VSGYs9
  4. http://ift.tt/1JWQ8ee
  5. http://ift.tt/1VSGZfM

Could someone help me please with writing a regular expression something that would generate all writers urls?

Thanks!

PCRE regex to remove empty braces

How can one write a regex to remove all pairs of braces that contain nothing?

For example, {} and {{}} should be reduced to an empty string, but {{} becomes { and {{A}{}} becomes {{A}}.

I'm currently running s/\{\}//g in a loop until the string length is fixed, but is there a better way to do this?

Regex to extract and parse an array like string in string

I have to create a script parse a path and replace variables with existing array attribute. I have an multi-deminsional array like below:

$param = array(
        'titles'=>array(
            '[group1]'=>array(
                array('name'=>'picture','title'=>'personel_image','target_folder'=>'tmp/contacts/{name=picture}[value]'),
                array('name'=>'full_name','title'=>'Full Name'),
                array('name'=>'melli_code','title'=>'id code','format'=>'number'),
                )
        )
)

As you can see there is an attribute call target_folder that user write as following format,'tmp/contacts/{format=number}[title]/{name=picture}[title]'.

I need a solution to parse a bold part of above path as an array like below.

$search_for = array(
        '0'=>array(
            '[array_column]'=>'format',
            '[array_column_keyword']=>'number',
            '[array_column_value']=>'title',
        ),
        '1'=>array(
            '[array_column]'=>'name',
            '[array_column_keyword']=>'picture',
            '[array_column_value']=>'title',
        )
)

What is the best way to resolve the above problem?

Java regular expression : how to get rid of text inside ()? [duplicate]

This question already has an answer here:

I have some text like this : Javascript (12+ years), Java (10 years) How to use regular expression to extract the following text : Javascript, Java

I've seen that link, have you tried it ? It doesn't work in my case ! The answer below works : replaceAll("\\((.+)\\)","")

Regex match the last part of a string

I want to add css file reference dynamically by onclick, which works fine now, but there is always a common css file being referenced multiple times, so I want to add a conditional branch, and also the url is absolute, which was intended to be modified to be relative.

The common css file name would always be a.css, could be in diff urls, so my plan is using Regex.

if (cssRef != /.*a.css$/){then add the css reference}

. anychar(url sign "/" would also match this I suppose)
* the previous char any time
$ end of the string

which is not working.

so, plz?

How to match everything after a word with javascript regex?

How can i match everything after a word(but not the word)?

Example:

enum Test
{
    // stuff
}

I want only Test to be found.

Thanks.

Jenkins Log Parser rule to exclude text between two strings

I'm using Jenkins log parser plugin to parse the console for errors. I'm trying to create a rule to OK a block of text between two strings without raising any flag.

I know ok /abc.*xyz/ rule works for single line.How do I extend this to a block of text or multiple lines like:
For example:

abc
... ...
... ...
... ...
xyz
Note: "xyz" is the first string that's matched after "abc"

I tried ok /abc(?s)(.*?)xyz/ but was unable to make it work.

Can anyone help me here?

Regex doesn't save match in variable

I got URLs to different Youtube channels stored in my database. I am now trying to loop through all of them and check whether they still exist with the following code:

foreach ($pages as $page) {
    preg_match("/([^/]+$)/", $page['url'], $channelId);

    $channel = get_data('http://ift.tt/1DgFG4b'.$channelId[0].'&key='.$site['yt_api']);

    $channel = json_decode($channel, true);

    echo $channelId[0];
    echo $channel[pageInfo][totalResults];

    break;
}

The problem is that this test code doesn't print out $channelId[0] but only $channel[pageInfo][totalResults] which is 0 in this case due to some error with my regex. Could someone point out my error please?

Best way to strip and untaint CGI values in Perl?

I'm writing a global subroutine to "wrap" CGI::param() and I want it to strip out characters based on situational "patterns." For example, if it's a session id it might require digits only. If it's an html page it might be letters, a period and possibly a dash. If it's a password it could allow digits, letters and some special characters.

I came up with this approach and want to know if there's a more elegant way to do it. And also if this would be acceptable security in an online application?

#!/usr/bin/perl -T

use strict;
use warnings;

my $x = shift || '';
my $y = ParamData($x,'d');
print "[$y]\n";
$y = ParamData($x,'w');
print "[$y]\n";
$y = ParamData($x,'dw');
print "[$y]\n";
$y = ParamData($x,'dw ');
print "[$y]\n";
$y = ParamData($x,'dw- .');
print "[$y]\n";
$y = ParamData($x,'w ');
print "[$y]\n";
exit(0);

sub ParamData {
  my $v = shift || return; # value
  my $p = shift || return; # pattern
  my $r = '';   # regex
  print "[$p] = ";
  foreach my $i (0 .. length($p) - 1) {
    my $c = substr($p,$i,1);
    for ($c) {
      /^d$/ and do { $r .= '0-9'; last; };
      /^w$/ and do { $r .= 'A-Za-z'; last; };
      /^ $/ and do { $r .= ' '; last; };
      /^-$/ and do { $r .= '-'; last; };
      /^\.$/ and do { $r .= '\.'; last; };
    }
  }
  $v =~ s/[^$r]//g;
  if ($v =~ /^([$r]).$/) {
    $v = $1; # untaint
  }
  return($v);
}

Here's output of a sample run:

$ ./paramdata.pl 'h.-1-.i m.2.o+m.3'
[d] = [123]
[w] = [himom]
[dw] = [h1im2om3]
[dw ] = [h1i m2om3]
[dw- .] = [h.-1-.i m.2.om.3]
[w ] = [hi mom]

What do you think? Thanks.

Split UNIX String with DOT delimiter and store in variable

I have a file abc.123.234.345 and I want to store value of 123.234.345 into variable1 using UNIX oneliner. Then I have to rename a file named def as def.123.234.345 I tried sed, awk but not able to generate split string.

I have to search as abc.*.*.* as string will be different every time.

Any suggestions?

Some sample that I use but not working

FILE=abc.*.*.* | mv /loc/PA_CSS_OPP.TRIGGER /loc/def.${FILE#*.}

Finding words in any order with regex

Considering this entries...

word1 word2 word3
word2 word3 word1
word3 word1 word2
other word1 word2
other word3 word1

I can match words 1, 2 e 3 in any order (first 3 lines) with:

^(^word1|^word2|^word3) (word1|word2|word3) (word1|$word2$|word3$)$

Note that i need to find exactly this words, nothing else. But when i have more words the expression grows a lot.

e.g. (with 4 words)

^(^word1|^word2|^word3|^word4) (word1|word2|word3|word4) (word1|word2|word3|word4) (word1|$word2$|word3$|word4$)$

My question is: is there any other simpler way to do this with regex?

Regex: Matching outer substring

I haven't been able to find an example of this. Given a string that contains a substring, I want to select just the outer string.

Example:

NumberLong("98237234234")

I want to select NumberLong("") and not the number inside the quotes. This way, I can do a find and replace inside IntelliJ to get rid of that and keep the number inside.

My current regex selects the whole thing:

(NumberLong\(")\d*("\))

Ambiguous regex selector for behat step

I am trying to match behat steps in the following formats (item, email or client could be swapped for other words).

I want to remove item 1
I want to remove email 4 from client 3

In SchemaContext I am matching with the following:

/**
* @Given /^I want to remove (.+) (\d+)$/
* @Given /^I want to remove (.+) (\d+) from (.+) (\d+)$/
*/
public function iWantToRemove($object, $object_id, $parent = false, $parentId = false) 
{
  // Do stuff.
}

But I get this error:

Ambiguous match of "I want to remove email 3 from client 4":
    to `/^I want to remove (.+) (\d+)$/` from SchemaContext::iWantToRemove()
    to `/^I want to remove (.+) (\d+) from (.+) (\d+)$/` from SchemaContext::iWantToRemove()

I'm struggling to find the correct regex / approach to match both formats correctly and run them through the same method. I'd appreciate any guidance.

PHP - searching string with database LIKE syntax/wildcards (%, _)

I have an application receiving search requests using the syntax of a database LIKE notation (ex: %someth_ng%), but I must be able to apply this search not only to a database (which is straightforward), but to strings in my application, which is in PHP.

I'm thinking that using a regex is probably the best way to do this, but I'd like to see what solutions other people can/have come up with.

Password validation with Regex

I am trying to get a different error for each type: missing uppercase, missing lower case, missing number, or space. The length seems to be the only thing working. I am guessing because it is at the start of the code. I have tried different variations and can't seem to get it working.

    <?php
    $Passwords = array(
"F!ve5",
"This !s12",
"w!zard12",
"W!ZARD12",
"W!zardJK",
"Wizard12",
"!Qazxsw2",
"@Wsxzaq1",
"@Wsxcde3",
"#Edcxsw2");

foreach ($Passwords as $StongPass) {
echo "<p>The Password &ldquo;" . $StongPass .
    "&rdquo; </p>";
if (strlen($StongPass)<8) 
    echo "Password is to short!";

elseif (strlen($StongPass)>16)
    echo "Password is to long!";

elseif (preg_match('/P[A-Z]/', $StongPass)) 
    echo "Password does not contain an upper case letter!";

elseif (preg_match('/P[a-z]/', $StongPass)) 
    echo "Password does not contain a lower case letter!";

elseif (preg_match('/P[!@#$%^&*()\-_=+{};:,<.>]/', $StongPass)) 
    echo "Password does not contain a special letter!";

elseif (preg_match('/P[0-9]/', $StongPass)) 
    echo "Password does not contain a number!";

elseif (preg_match('/P[""]/', $StongPass)) 
    echo "Password cannot contain any spaces!";

else 
    echo "Password is strong!";

    }
    ?>

The results look like this "The Password “F!ve5” Password is to short! The Password “This !s12” Password is strong! The Password “w!zard12” Password is strong! The Password “W!ZARD12” Password is strong!"

Extracting strings from one long string

I have a string like this

"[0.01,3.45],[5.674,8.712],[4.321,8.892],[3.412,6.781]"

I need to extract each pair of numbers so that each pair is a separate string in a String array

i.e. I want: {"0.01,3.45","5.674,8.712","4.321.8.892","3.412,6.781"}

This is the code I have:

    Pattern pattern = Pattern.compile("\\[(.*?)\\]");
    String[] result = pattern.split(myString);

.. and I get {"",",",",",","}

I have tried some different regex expressions as well but they just gave me an array with ONE (long) string element which obviously something I don't want either

Is the problem the regex expression or should I be using different code?

Thanks.

Scrapy rules and regular expression

I'm trying to use Scrapy to scrap information from geonames.org. More specifically, I want to retrieve the 10 largest cities for each country. My starting URL is http://ift.tt/1llrHys. On this page, I want to follow each URL that meets the regex:

/countries/\w{2}/..html

Then on followed pages (that is the country pages), I want to follow the URL with the following structure http://ift.tt/pxPylTXX/largest-cities-in-YYYY.html where XX is the two letter country code and YYYY is the actual name of the country which obviously can be of variable length. The code below doesn't work. I suspect it's due to a problem with the regex of the second rule. But maybe not!

from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors import LinkExtractor
import re
import os

class MySpider(CrawlSpider):
    name = 'geocodeSpider'
    allowed_domains = ['www.geonames.org']
    start_urls = ['http://ift.tt/1llrHys']

    fileName="largest_cities.txt"    
    try:
        os.remove(os.path.join('geocode/output',fileName))
    except OSError:
        pass
    rules = (
        Rule(LinkExtractor(allow=(r'/countries/\w{2}/.\.html', )),),
        Rule(LinkExtractor(allow=(r'/\w{2}/largest-cities-in-.\.html', )), callback='parse_item'),
  )


    def parse_item(self, response):
...

Thanks a lot for your help!!

TG

javascript regular expression for -999x999

I need a regular expression for:

-[n digits]x[n digits]

I already tried this:

var s = "path/path/name-799x1024.jpg"; 
s.replace(/\d/g, "");

But this gets only the digits. Here is a small jsfiddle: http://ift.tt/1LYqYlr

The outcome I try to get is:

pfad/pfade/name.jpg

How do I add the - and the small x between the two digits?

Understanding some JavaScript with a RegExp

I have the following js code

var regex = new RegExp('([\'"]?)((?:\\\\\\1|.)+?)\\1(,|$)', 'g'),
key = regex.exec( m ),
val = regex.exec( m );

I would like to understand it. In particular:

  • why there are all those backslash in the definition of the RegExp? I can clearly see that \\1 is a reference to the first saved element. Why in a new RegExp using ' and not " we need to use \\1 and not simple \1?

  • why there is a comma between the two definitions of key and val? I may guess that it depends on the "instances" finded using "g", but it is not very clear anyway to me.

I tried to execute the code with

m = 'batman, robin' 

and the result is pretty a mess, and I cannot really explain it very well.

How to know if current culture in ASP.Net Webforms app is based on English alphabets

I have a regular expression validator in an ASP.Net Webforms app that makes sure the input in a textbox is a combination of these characters alphabets, digits, period, hyphen and single quote as in code below. Since this ASP.Net is multi-lingual i.e. both English and non-English cultures are allowed, the regex validator will need to b disabled when its being accessed from a non-English culture.

Question

Is the code-behind mentioned below going to satisfy this requirement of disabling the regex validator when being accessed from a non-English culture, Or is the code lacking something?

Regex Validator

<asp:RegularExpressionValidator 
ID="revProdName" runat="server" 
ErrorMessage="RegularExpressionValidator" ControlToValidate="ctxtProductName" 
ValidationExpression="^[(a-z)(A-Z) .'-(0-9)]+$"></asp:RegularExpressionValidator>

Code-behind of page

 If System.Globalization.CultureInfo.CurrentUICulture.DisplayName.StartsWith("en-") Then
            revProdName.Enabled = True
        Else
            revProdName.Enabled = False
        End If

preg_match_all rtmp links and its titles

Hi all there I have this string:

All text has PHP_EOL at end of its line.
Some TITLE OF RTMP STREAM
rtmp://slww/best
Some simple text what not required to find
Another not required string line

Used this regex to get rtmp or http links but how can i find its titles?

preg_match_all("/(rtmp:+\S*)|(http:+\S*)/s", $input_lines, $output_array);

That rtmp or html regex works correctly but i need to capture titles of rtmp links too.

Have tried to add ^.*$^ followed by my rtmp http pattern , as ^ its start of line and $ its end of it. And /s option for search multiple lines including new line characters.

/^.*$^(rtmp:+\S*)|(http:+\S*)/s

But can not figure it out how can i find its title. Simple what i have tried to archive is to get whole line above my regex or below my regex.

In some cases i need to grab whole line below.

Any thoughts?

Regex in Custom Configuration Partially Working

I have a ConfigurationProperty that is annotated with a RegexStringValidator that looks like this:

public class Test : ConfigurationElement
{
    [ConfigurationProperty("field", IsKey = true)]
    [RegexStringValidator("issuer|subject")]
    public string Field
    {
        get { return (string)base["field"]; }
    }
}

It always throws an exception saying that the RegexStringValidator failed. I can achieve success if I change the regex value to either of these:

  • "[a-zA-Z]*"
  • ".*"

The actual "field" value being validated is the simple string "issuer". I can see no reason why there should be a problem. In fact, the source code for RegexStringValidator does nothing fancy; it simply uses a Regex and checks for success.

So I tried to do the regex directly as a test, the same way that it is done inside RegexStringValidator:

Regex reg = new Regex(@"issuer|subject", RegexOptions.Compiled);
bool match = reg.Match("issuer").Success;

The above works as expected; it returns Success==true. I even used Telerik's "Just Decompile" to verify the System.Configuration source code indeed matches what is published online.

Again, I can see no reason why my "issuer|subject" RegexStringValidator regex constantly fails.

Any ideas?

The only clue I've turned up is when I tried the regex "[a-zA-Z]". Strangely, this failed because it did not have the trailing asterisk. So perhaps the regex must be written to match the full-length of the input. To test that theory, I changed my regex to "^issuer$|^subject$", but that still didn't work when applied to the RegexStringValidator. It does, however, work with my explicitly written regex test.

What makes the above anomaly interesting is that the source code for RegexStringValidator gives no reason of why "[a-zA-Z]" would fail. Does this imply that the code I'm reflecting and seeing online does not match what is actually executing on my machine? That doesn't seem plausible. So this is weird indeed...

I'm using a .net 4.0 build, on a machine that has .net 4.5 installed.

redirecting an .htaccess with regular expression

There are SO many .htaccess redirect posts on here, but unfortunately none that match my situation that I can find, and I'm struggling with understanding regular expressions to make this work. My situation:

Rebuilt a real estate site on Wordpress. The site had been established for many years before, and therefor had a ton of Google-crawled property URLs. The new site uses a completely different permalink structure with brand new properties and google search console is coming up with tons of 404 errors.

Old structure: http://ift.tt/1M24PTt New structure: http://ift.tt/1I8mQv9

I'd like to be able to write a .htaccess redirect to point ALL URLs that start with /0000/00/00/whatever to the home page. I've done some research onregular expressions and I've found similar cases but none that I can make work for me. They seem to just be ignored.

Guide site that I used: http://ift.tt/1M24Q9H

My relevant .htaccess code:

# BEGIN custom rewrite rules
RewriteEngine On
RewriteRule ^[0-9]{4}/[0-9]{2}/[0-9]{2}/.*/$ http://ift.tt/1I8mQvd [R=301]
# END custom rewrite rules

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Basically my custom redirect is a result of hacking together multiple tutorials on regular expression to try to match the relevant "old" urls. Can someone help me figure this one out? Is my custom redirect in the wrong place? (does it need to be AFTER the wordpress redirect code)? Help would be appreciated!

Dan

What is the equalient of JavaScript's "s.replace(/[^\w]+/g, '-')" in Dart language?

I am trying to get the following working code in JavaScript also working in Dart.

http://ift.tt/1UddDam

var s = "We live, on the # planet    earth";
var results = s.replace(/[^\w]+/g, '-');

document.getElementById("output").innerHTML = results;

Which gives the output

We-live-on-the-planet-earth

I have tried this Dart code

void main() {
    print( "We live, on the # planet    earth".replaceAll("[^\w]+","-"));
}

But the output becomes the same.

What am I missing here?

Express.js route and regex

I have an object like this :

geo: {
        description: 'Geolocalisation',
        properties: {
            latitude: {type: 'number'},
            longitude: {type: 'number'}
        }
    }

I want to create routes to retrive a nested object like :

host/geo.schema or host/geo.json

to get the entire object

host/geo/properties.schema or host/geo/properties.json

to get

properties: {
            latitude: {type: 'number'},
            longitude: {type: 'number'}
        }

How do I preg_match a certain string of numbers in a string [on hold]

This is probably pretty simple, but I can't seem to do it.

I need to pull out the 5.5.8 from this string:

XM.ar7240.v5.5.8.20795.140123.1700

Edit: My Regex is really rusty, so I really don't know where to start. I tried to count to the 12th position and then pull out the next 5 characters, but that didn't work at all.

    preg_match("/{0,12}[^*]/", $firmware_version, $matches);
  {
      print_r($matches);
  }

I was able to use this, but sometimes the version is 5.5.9, or 5.6.2, etc...

  preg_match("/5.5.8/", $firmware_version, $matches);
      {
          print_r($matches);
      }

Replace all character matches that are not escaped with backslash

I am using regex to replace ( in other regexes (or regexs?) with (?: to turn them into non-matching groups. My expression assumes that no (?X structures are used and looks like this:

(
  [^\\]     - Not backslash character
  |^        - Or string beginning
)
(?:
  [\(]      - a bracket
)

Unfortunatelly this doesn't work in case that there are two matches next to each other, like in this case: how((\s+can|\s+do)(\s+i)?)?

image description

With lookbehinds, the solution is easy:

/(?<=[^\\]|^)[\(]/g

But javascript doesn't support lookbehinds, so what can I do? My searches didn't bring any easy universal lookbehind alternative.

How to extract a portion of a file in shell script

I have a log file and i have to parse them. i want to extract a portion of this log file means that between two regular expression anything comes would be able to capture . Like

reg="(COPY\s+role\s+\(id\,\s+name\,\s+access\_level.*)"

and

regex="END"

all lines that comes between these two regular expression should able to capture. For this i have tried

echo "Enter the file to extract"
read file

reg="(COPY\s+role\s+\(id\,\s+name\,\s+access\_level.*)"
regex="END"

if [[ $file =~ $reg ]];then
 while read LINE

 echo ${BASH_REMATCH[1]}
if[[ $LINE =~ $regex ]];then
break;
fi
 done < $file

but i am not able to capture anything .Please suggest what to do .If i am making it more complicated than suggest me how to do this.

I am looking for a sql query to exclude records in sql that are not a filename and is liget file's extension

sample data is like below(5 rows):

e:\deploy\applications\intel management engine interface and serial over lan driver (sol) driver 7.1.2.1041v2\me_sw\mewmiprov\me\cim_schema\system\cim_computersystemdma.mof
c:\$recycle.bin\s-1-5-21-3125639655-2069970247-2443061104-29869\$iqzvjd6.jpg
c:\users\asdf\music\the cranberries\no need to argue\02 i can't be with you.mp3
e:\oracle\epm\docs\epm~1.111\wa_user\about_navigating_data_objects.html
Marijuana; Suicide; ass; butt; don’t say anything; drug; kick; knife; knives; marijuana; murder; naked; opiate; party; prick; scam; sex; smoke; smoke a joint; smoking; sneak; speculation; stabbed; stoned; suck; tripping

Apparently the last one is NOT a legitimate file and the others are. Can anyone help? Thank you very much

Replace file name with simple python regex script (for Automator)

I would like to create an automator folder action to rename files that I add in.

Basically, my files are named like that :

SOMETEXT-A00B00-ANOTHERTEXT.extension

To create and run an automator action that rename a file isn't a problem, but I would like to use regex (in Python if possible, 'cause i'm not familiar with apple script or batch) to rename the file like that :

A00B00.extension

Any idea ?

Deprecated left curly bracket in perl regex - exactly when?

perldoc perlre says this

(If a curly bracket occurs in any other context and does not form part of a backslashed sequence like \x{...} , it is treated as a regular character. However, a deprecation warning is raised for all such occurrences, and in Perl v5.26, literal uses of a curly bracket will be required to be escaped, say by preceding them with a backslash ("{" ) or enclosing them within square brackets ("[{]" ). This change will allow for future syntax extensions (like making the lower bound of a quantifier optional), and better error checking of quantifiers.)

OK, so the following prints the deprecation message.

perl -lE 'm/x{x}/'

why the following isn't?

perl -lE 'm/x({x})/'

e.g. in the capture group is the { allowed unescaped? Probably not because the

perl -lE 'm/x(x{x})/'

also prints the warning.

So, what is the exact "logic"?

Ps: i will escape every literal {, but wondering about the rationale behind the above.

Regex works on Rubular, but appears to not in RSpec test

I am currently working on these tests. Right now the first 2 will pass but the 3rd one will not.

context "Navigation Functions" do
  let(:nav) {Navigator.new("8801507-001")}
  it "#nav_to_start_folder should navigate to job folder based on stored Work Order number" do
    nav.nav_to_start_folder
    expect(File.basename(Dir.pwd)).to eq("8801507-001 Test Dealer 1 of 4")
  end

  it "#input_csv should return the input CSV when in a folder" do
    expect(nav.input_csv).to eq("test.csv")
  end

  it "#nav_to_next_folder should increment the work order number and job title and create the next folder" do
    nav.nav_to_next_folder
    expect(File.basename(Dir.pwd)).to eq("8801507-002 Test Dealer 2 of 4")
  end
end

The class I am testing is as follows:

class Navigator
def initialize(starting_work_order)
  @workorder = starting_work_order
end

def nav_to_start_folder
  Dir.chdir @workorder[0, 7]
  Dir.chdir Dir.glob("#{@workorder}*").at(0)
end

def input_csv
  arr = Dir.glob('*.csv')
  arr.delete_if { |e| /880\d\d\d\d-\d\d\d ?(for import)?/ =~ e }
  arr.at(0)
end

def nav_to_next_folder
  @title = job_title(File.basename(Dir.pwd))
  Dir.chdir '..'
  next_work_order_number
  next_job_title
  Dir.mkdir @workorder + " " + @title
  Dir.chdir @workorder + " " + @title
end

private

# Info Parser
def next_work_order_number
  @workorder[-3, 3] = next_work_order_seq
end
# Info Parser
def next_work_order_seq
  start_number = @workorder[-3, 3].to_i
  format('%03d', (start_number + 1))
end

# Info Parser
def ipd_style?(folder_name)
  if folder_name[3] == '-'
    false
  else
    true
  end
end

# Info Parser
def job_title(folder_name)
  if ipd_style?(folder_name)
    folder_name[12, (folder_name.length - 11)]
  else
    folder_name[11, (folder_name.length - 10)]
  end
end

# Info Parser
def next_job_title
  /\A(\d*-\d{3}) (?<mainTitle>.+) (?<current>\d+) of (?<total>\d+)\z/ =~ @title
  @title = "#{mainTitle} #{(current.to_i + 1).to_s} of #{total}"
end

end

What appears to be happening is whenever I run next_job_title the regex match groups all come up as nil. I have tested the expression against a few test strings and they all appear to work, but for some reason in this test it won't. Am I missing something subtle (or obvious) about match groups that is causing this to not work?

Also the RSpec failure message is:

 IPDUtils::Navigator Navigation Functions #nav_to_next_folder should increment the work order number and job title and create the next folder
 Failure/Error: expect(File.basename(Dir.pwd)).to eq("8801507-002 Test Dealer 2 of 4")

   expected: "8801507-002 Test Dealer 2 of 4"
        got: "8801507-002  1 of"