1

Suppose I have the string: BLAH BLAH BLAH copy 2. I want to find the index of the two pieces, the word 'copy' and a number that may follow the word copy.

I have the regex: /(copy)\s+([0-9]+)$/i which successfully matches copy and 2 from the above string. How can I find the index of the number 2? I know I can use .index to find the position of the matched test 'copy 2', but I would like to get the position of '2' so that I can increment it.

4 Answers 4

1

If you need to replace the copy number with an incremented number, use replace plus a replacer function:

'BLAH BLAH BLAH copy 2'.replace(/(copy )(\d+)/, function (s, s1, s2) {
    return s1 + (Number(s2) + 1);
});
Sign up to request clarification or add additional context in comments.

Comments

1

If you modify the regular expression slightly, the index of the number can be computed:

var matches = "BLAH BLAH BLAH copy 2".match(/(copy)(\s+)([0-9]+)$/i);
var numberIndex = matches.index + matches[1].length + matches[2].length;

But you really do not need that in order to increment the number:

var matches = "BLAH BLAH BLAH copy 2".match(/(copy)\s+([0-9]+)$/i);
var incremented = (+matches[2]) + 1;

Comments

1

You should go with regex /^(.*?copy\s+)(\d+)$/i and then length of $1 is a position of $2 (copy number).

Edit: Your test code is (fiddle):

var str = "BLAH BLAH BLAH copy 2";
var m = str.match(/^(.*?copy\s+)(\d+)$/i);
alert("Found '" + m[2] + "' at position " + m[1].length);

8 Comments

Not always. \s+ means there could be 1 or more spaces.
No, you do not know how much whitespace there is.
Yes, it will work always, regardless of how many whitespace characters are there :)
My comment was posted well before you updated your answer. Apropos, I see no good reason for inserting .*? here, which is not backwards- compatible, and the ^ anchor that also was not in the original expression.
@PointedEars - Well, .*? may be changed to .* if there is $ (don't know if OP wants allow some extra text behind copy N), but how the hell you want to get index by length of $1 without ^..? Teach me!
|
0

Change the regex /(copy)\s+([0-9]+)$/i to /^((.*)(copy)\s+)([0-9]+)$/i

Then the position of copy is the length of $2 and the position of the numbers is the length of $1. The number will be in $4

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.