2

My string is like

5blog5sett5ings5[5slider5][5][5ima5ge5]

I like to match any digit into second brackets from end by regular expression.

For this case, my target digit is 5 into [5].

I like to select where before pattern like
5blog5sett5ings5[5slider5][ and after pattern like ][5ima5ge5]

I will use it for JavaScript string replace. Text can be different but the before and after patterns are like that. For better understanding see the image.

enter image description here

I tried something like

(?<=.+[.+?][)\d(?=][.+?])

but did not work.

7
  • What have you tried so far? Which programing language are you using? Commented May 21, 2017 at 11:51
  • Why do you think regular expressions are the answer here, instead of string replacements? Commented May 21, 2017 at 11:52
  • What replacement do you actually want to do? Commented May 21, 2017 at 11:53
  • I tried something like (?<=.+[.+?][)\d(?=][.+?]) but did not work. Commented May 21, 2017 at 11:56
  • If you just want to match the digit, try \d+(?=]\[[^\]]*]$) Commented May 21, 2017 at 12:00

3 Answers 3

1

I think you could just use a lookahead to check if there ] and one more [ ] ahead until end.

\d+(?=]\[[^\]]*]$)

See demo at regex101

(be aware that lookbehind you tried is not available in js regex)

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

Comments

1

I guess you can use:

\[(\d+)\][^\]]+]$

Regex Demo & Explanation

var myString = "5blog5sett5ings5[5slider5][5][5ima5ge5]";
var myRegexp = /\[(\d+)\][^\]]+]$/mg;
var match = myRegexp.exec(myString);
console.log(match[1]);

3 Comments

The OP wants only the number 5 to be matched.
@horcrux it matches on group 1.
Sry, you are right, regex101 shows only the group 0.
0

Use this:

^.*\[(\d*)\]\[[^\]]*\]$

Where:

  • ^ is the begin of the string
  • .* means any character
  • \[ and \] matches literal squared brackets
  • (\d*) is what you want to match
  • [^\]]* is the content of the last couple of brackets
  • $ is the end of the string

See an example:

var str = "5blog5sett5ings5[5slider5][5][5ima5ge5]";
var res = str.match(/^.*\[(\d*)\]\[[^\]]*\]$/);
console.log(res[1])

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.