1

How do I write a regex to get the 5 characters 572f0 from the below url?

The regex I built is dep_id=([^&]*) but this assumes that there will be a & after the value and I would like to just always match and retrive the 5 characters after dep_id=

https://test.com/Chat/test?language=en_US#dep_id=572f0&org_id=00Df0&

HSG
  • 193
  • 1
  • 2
  • 9

3 Answers3

3

Not Regex, but

var x = "https://test.com/Chat/test?language=en_US#dep_id=572f0&org_id=00Df0&"
x.split("dep_id=")[1].substr(0,5)
dave
  • 62,300
  • 5
  • 72
  • 93
  • An important note: this solution relies on presence of `dep_id=` in the string and fails with error otherwise. – zerkms Jul 02 '14 at 22:53
  • 1
    @zerkms, that's accurate, but adding error handling would be trivial. – Adam Jul 02 '14 at 22:56
  • @Adam: indeed, but it will inflate the code, which will make the regex "better" solution. Btw, it is also not clear what to do if the `dep_id` parameter value is shorter than 5 characters. With regex it's easy to handle. With this code - it won't be. – zerkms Jul 02 '14 at 22:57
2

If you want to match 5 characters:

/dep_id=(.....)/

or

/dep_id=(.{5})/

If you want to match until & or the end:

/dep_id=([^&]+)/

Your initial regex was actually totally valid: it does not require a & to follow. It takes everything until a & or the end...

jcaron
  • 17,302
  • 6
  • 32
  • 46
1

To retrieve the five chars directly, use this:

var myregex = /dep_id=([^#&\s]{5})/m;
var match = myregex.exec(str);
if (match != null) {
    result = match[1];
} else {
    result = "";
}

Explanation

  • dep_id= matches literal characters
  • ([^#&\s]{5}) captures to Group 1 five chars that are not a &, url fragment delimiter # or whitespace

This retrieves the characters directly from the Group 1 capture.

zx81
  • 41,100
  • 9
  • 89
  • 105
  • I'm capped on rep for the day so I am just observing. +1 for the edit. – hwnd Jul 02 '14 at 22:59
  • @hwnd the reason for `[^#&\s]` is that if we just take `.{5}`, we might start eating into another `&...`, or a url fragment `#...`, or past the end of the url. – zx81 Jul 02 '14 at 23:13
  • @hwnd I hear you... I don't always trust problem descriptions 100%, so `[^#&\s]` works for me. :) – zx81 Jul 02 '14 at 23:18