Replacing Numbers in a String

How to replace all numbers in java string

The correct RegEx for selecting all numbers would be just [0-9], you can skip the +, since you use replaceAll.

However, your usage of replaceAll is wrong, it's defined as follows: replaceAll(String regex, String replacement). The correct code in your example would be: replaceAll("[0-9]", "").

Replace numbers in String Javascript

const dataString = JSON.stringify(dataArray);    
const regex = /<span.*?>|<\/span>/gm;
const newData = dataString.replace(regex,'');


This should do it.

TypeScript: How to replace a particular number in a string, and then update its value?

Try something like this.
Below code takes care of carry.

const givenStr = "3345678901";

let givenStrArray = givenStr.split('').map(Number);

const inputIndex = 4;
const increaseAmount = 2;

let givenStrNumber = 0;

for (let i = 0; i < givenStrArray.length; i++) {
givenStrNumber += givenStrArray[i] * Math.pow(10, givenStrArray.length - i - 1)

givenStrNumber += increaseAmount * Math.pow(10, givenStrArray.length - inputIndex - 1)


PHP str_replace not correctly replacing number to string

Str_replace() function replaces some characters with some other characters in a string.

Do you really have to work with str_replace? otherwise just do it with an array:

$numbers = [
1 => "one",
15 => "fifteen",

echo $numbers[15];

How to replace numbers in a string with numbers from another list?

The accepted answer is actually incorrect (it is now deleted). data.replace() will replace the first occurrence of the number, which is not always the correct one. For example, when you try to replace 8 with 14, it actually replaces 58 with 514.

Here is my solution:

import re

data = 'readingOrder {index:24;} person {offset:0; length:7;} textStyle {offset:0; length:7; underlined:true;} place {offset:52; length:8;} textStyle {offset:52; length:8; underlined:true;}'
new_numbers = [24, 0, 12, 0, 12, 58, 14, 58, 14]

offset = 0
for index, match in enumerate(re.finditer('\d+', data)):
data = data[:match.start() + offset] + str(new_numbers[index]) + data[match.end() + offset:]
offset += len(str(new_numbers[index])) - match.end() + match.start()

PHP : how to replace numbers in a string with the exact given value

Telling the difference between whole words and parts of a word sounds like a task for regexp, so here's my take(To be specific: Add regexp word boundaries \b for the patterns):

$attribute_ids = array(200,201);
$attribute_names = array("David","Rimma");
$string = "200 2006-2009 boy, 201 girl";

echo preg_replace(
array_map(fn($item) => "/\b$item\b/", $attribute_ids),
); // David 2006-2009 boy, Rimma girl

I'm not sure whether the mapping should be done outside or inside the call to array_map(). As it is now the code is kind of confined to whole word patterns. But on the other hand, if that's ok for the task at hand or the array of patterns is huge then it could be useful :)..

Related Topics

Leave a reply