0

Say I have a string:

\foo\junk\f0\morejunk\

How can I extract 'f0' from it using regex? I essentially only want to match an 'f' followed by a number, without it getting caught on strings beginning with 'f' not followed by a number.

I have tried the following:

(?<=f)(\d*)

But this gets stuck on the first 'f' in the string, 'foo' and doesn't match the latter case of 'f0'. How can I put a quantifier on a lookbehind to match the string I want?

another option could be to split the string by the '\' delimiter and try to match each split, but this seems unnecessary?

2
  • Ah I was using the wrong quantifier, thank you for pointing out my stupidity Commented Nov 11, 2015 at 11:08
  • Not just quantifier, complete regex Commented Nov 11, 2015 at 11:10

3 Answers 3

2

Look behind is not supported in JavaScript regex. You can use capture group. Also use + instead of *, since * matches 0 or more characters while + will match one or more of the preceding character.

var str='\\foo\\junk\\f0\\morejunk\\';
var res=str.match(/\\f(\d+)\\/)[1];
alert(res);

Update : If you want to match entire string then just use /f\d+/ no need of capturing group

var str='\\foo\\junk\\f0\\morejunk\\';
var res=str.match(/\\(f\d+)\\/)[1];
alert(res);

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your explination
"How can I extract 'f0' from it using regex?", use /(f\d+)/.
match(/f\d+/)[0] for extracting entire string
This one is wrong. Such pattern will match any string like \foo\junk\junkf0junk\morejunk\. My solution posted below/above.
1

Why not simply:

/(f\d+)/

It matches f followed by one or more digits. The result is in group 1.

3 Comments

Apply this pattern for \foo\junk\junkf0junk\morejunk\
@MaxZuber: well, it gives f0, so what?
According the last paragraph of the question, it should be junkf0junk and it doesn't match the pattern then
0
var string = '\\foo\\junk\\f0\\morejunk\\';
var expression = /\\(f(\d+))\\/;
var matches_array = string.match(expression);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.