webHasan
webHasan

Reputation: 481

Match by regular expression to string replace by JavaScript

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.

Upvotes: 2

Views: 72

Answers (3)

bobble bubble
bobble bubble

Reputation: 18490

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)

Upvotes: 1

Pedro Lobito
Pedro Lobito

Reputation: 98871

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]);

Upvotes: 1

logi-kal
logi-kal

Reputation: 7880

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])

Upvotes: 0

Related Questions