Home > Net >  Replace text between first bracket and . without removing the bracket and
Replace text between first bracket and . without removing the bracket and

Time:11-02

I would like to replace the 70 in between the brackets with a specific string lets say '80'.

from filter[70.00-100.00] --> filter[80.00-100.00]

However when using the following code:

str_replace('filter [70.00-140.00]'," *\\[.*?\\. *",'80')

The output is:

filter8000-140.00]

Is there any way to replace the string between the \ and . (in this case 70) without removing the \ and . ?

CodePudding user response:

To replace any one or more digits after [ use

library(stringr)
str_replace('filter [70.00-140.00]','(?<=\\[)\\d ', '80')
sub('\\[\\d ', '[80', 'filter [70.00-140.00]')
sub('(?<=\\[)\\d ', '80', 'filter [70.00-140.00]', perl=TRUE)

See the online R demo. The (?<=\[)\d matches a location immediately preceded with [ and then one or more digits. \[\d matches [ and one or more digits, so [ must be restored and thus is added into the replacement pattern.

To replace exactly 70, you can use

library(stringr)
str_replace('filter [70.00-140.00]',"(\\[[^\\]\\[]*)70",'\\180')
# => [1] "filter [80.00-140.00]"

sub('(\\[[^][]*)70','\\180', 'filter [70.00-140.00]')
# => [1] "filter [80.00-140.00]"

See the regex demo. Details:

  • (\[[^\]\[]*) - Group 1: [, then zero or more chars other than [ and ]
  • 70 - a 70 string.

In the replacement, \1 inserts Group 1 value.

Another solution could be replacing all occurrences of 70 strings inside square brackets that end with a word boundary and are not preceeded with a digit or digit . (that is, to only match 70 as a whole integer part of a number) with

str_replace_all(
  'filter [70.00-140.00]',
  '\\[[^\\]\\[]*]',
  function(x) gsub('(?<!\\d|\\d\\.)70\\b', '80', x, perl=TRUE))
# => [1] "filter [80.00-140.00]"

Here, \[[^\]\[]*] matches strings between two square brackets having no other square brackets in between and the gsub('(?<!\\d|\\d\\.)70\\b', '80', x, perl=TRUE) is run on the these matched substrings only. The (?<!\d|\d\.)70\b matches any 70 that is not preceded with digit or digit . and is not followed by another word char (letter, digit or _, or connector punctuation, since ICU regexps are Unicode aware by default).

CodePudding user response:

You can use this. It will replace all digits between the [ and the . :

preg_replace('/(?<=\[)(\d*)(?=\.)/', '80', 'filter [70.00-140.00]');
  • Related