Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace part of a string using regex

i need to replace a part of a string in Javascript

The following example should clarify what i mean

var str = "asd[595442/A][30327][0]";
var strToReplace = "30333";

var strDesiredResult = "asd[595442/A][30333][0]";

Basically it means the second area within the brackets should get replaced with another string

How to do that?

What i did so far is something like this :

var str = "asd[595442/A][30327][0]";
var regex = /asd\[(.*)\]\[(.*)\]\[(.*)\]/;
var arrMatches = regex.exec(str);

The string appears in arrMatches[2] correctly, and i could replace this. But what happens if in arrMatches[1] is the same string ?

Because it should only replace the value in the second bracket area.

like image 684
sintakonte Avatar asked Apr 28 '17 08:04

sintakonte


People also ask

How do you replace a section of a string in regex?

To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring. The string 3foobar4 matches the regex /\d. *\d/ , so it is replaced.

How do you replace a part of a string with another string?

Replace part of a string with another string in C++ There is a function called string. replace(). This replace function replaces only the first occurrence of the match.

Can I use regex in replace?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.


2 Answers

You may use a regex that will match the first [....] followed with [ and capture that part into a group (that you will be able to refer to via a backreference), and then match 1+ chars other than ] to replace them with your replacement:

var str = "asd[595442/A][30327][0]";
var strToReplace = "30333";
console.log(str.replace(/(\[[^\]]*]\[)[^\]]*/, "$1" + strToReplace));

var strDesiredResult = "asd[595442/A][30333][0]";
console.log(strDesiredResult);

The /(\[[^\]]*]\[)[^\]]*/ has no gmodifier, it will be looking for one match only.

Since regex engine searches a string for a match from left to right, you will get the first match from the left.

The \[[^\]]*]\[ matches [, then any 0+ chars other than ] and then ][. The (...) forms a capturing group #1, it will remember the value that you will be able to get into the replacement with $1 backreference. [^\]]* matches 0+ chars other than ] and this will be replaced.

Details:

  • ( - a capturing group start
    • \[ - a literal [ symbol (if unescaped, it starts a character class)
    • [^\]]* - a negated character class that matches zero or more (due to the * quantifier)
    • ] - a literal ] (outside a character class, it does not have to be escaped)
    • \[ - a literal [
  • ) - end of capturing group #1 (its value can be accessed with $1 backreference from the replacement pattern)
  • [^\]]* - 0+ (as the * quantifier matches zero or more occurrences, replace with + if you need to only match where there is 1 or more occurrences) chars other than ] (inside a character class in JS regex, ] must be escaped in any position).
like image 149
Wiktor Stribiżew Avatar answered Sep 17 '22 01:09

Wiktor Stribiżew


Use this pattern:

'asd[595442/A][30327][0]'.replace(/^(asd\[[^\[\]]+\]\[)([^\[\]]+)(\]\[0\])$/, '$130333$3')

Test here

^            - match beginning of string
first group  - match "asd[", any chars except [ and ], "]["
second group - match any chars except [ and ]
third group  - match exactly: "][0]"
$            - match end of string
like image 23
yivo Avatar answered Sep 18 '22 01:09

yivo