HippoDuck
HippoDuck

Reputation: 2194

JQuery match with RegEx not working

I have a filename that will be something along the lines of this:

Annual-GDS-Valuation-30th-Dec-2016-082564K.docx

It will contain 5 numbers followed by a single letter, but it may be in a different position in the file name. The leading zero may or may not be there, but it is not required.

This is the code I come up with after checking examples, however SelectedFileClientID is always null

var SelectedFileClientID = files.match(/^d{5}\[a-zA-Z]{1}$/);

I'm not sure what is it I am doing wrong.

Edit:

The 0 has nothing to do with the code I am trying to extract. It may or may not be there, and it could even be a completely different character, or more than one, but has nothing to do with it at all. The client has decided they want to put additional characters there.

Upvotes: 1

Views: 5425

Answers (4)

Pawan
Pawan

Reputation: 3864

Try - 0?\d{5}[azA-Z] As you mentioned 0 may or may not be there. so 0? will take that into account.

Alternatively it can be done like this. which can match any random character.

(\w+|\W+|\d+)?\d{5}[azA-Z]

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

There are at least 3 issues with your regex: 1) the pattern is enclosed with anchors, and thus requires a full string match, 2) the d matches a letter d, not a digit, you need \d to match a digit, 3) a \[ matches a literal [, so the character class is ruined.

Use

/\d{5}[a-zA-Z]/

Details:

  • \d{5} - 5 digits
  • [a-zA-Z] - an ASCII letter

JS demo:

var s = 'Annual-GDS-Valuation-30th-Dec-2016-082564K.docx';
var m = s.match(/\d{5}[a-zA-Z]/);
console.log(m[0]);

Upvotes: 1

Srinivas Ch
Srinivas Ch

Reputation: 66

Try this pattern , \d{5}[a-zA-Z]

Upvotes: 0

nibnut
nibnut

Reputation: 3127

All right, there are a few things wrong...

var matches = files.match(/\-0?(\d{5}[a-zA-Z])\.[a-z]{3,}$/);
var SelectedFileClientID = matches ? matches[1] : '';

So:

  1. First, I get the matches on your string -- .match()
  2. Then, your file name will not start with the digits - so drop the ^
  3. You had forgotten the backslash for digits: \d
  4. Do not backslash your square bracket - it's here used as a regular expression token
  5. no need for the {1} for your letters: the square bracket content is enough as it will match one, and only one letter.

Hope this helps!

Upvotes: 0

Related Questions