Replace First Occurrence of Pattern in a String

Replace first occurrence of pattern in a string

I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...

var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);

Replace the first occurrence of a pattern in a String

Use replacen

Replaces first N matches of a pattern with another string.

replacen creates a new String, and copies the data from this string
slice into it. While doing so, it attempts to find matches of a
pattern. If it finds any, it replaces them with the replacement string
slice at most count times.

let input = "Life is Life".to_string();
let output = input.replacen("Life", "My wife", 1);

assert_eq!("My wife is Life", output);

Rust Playground

Replace the first occurrence of a character within a string in R

The g in gsub stands for global, indicating that it will match all occurrences. If you use sub instead of gsub, only the first occurrence will be matched and replaced. See ?gsub for details, in the Description:

sub and gsub perform replacement of the first and all matches respectively.

And, if you only want to replace the colon, your pattern should just be ":", ".*:" will match and replace everything up through the last colon. If you want to replace everything up through the first colon, using sub and ? to make * not greedy will work.

x = "Request(123): \n Element1: 123123 \n Element2: 456456"

## match everything up through last colon
sub(".*:", "", x)
# [1] " 456456"

## not greedy, match everything up through first colon
sub(".*?:", "", x)
# [1] " \n Element1: 123123 \n Element2: 456456"

## match first colon only
## since we don't need regex here, fixed = TRUE will speed things up
sub(":", "", x, fixed = TRUE)
#[1] "Request(123) \n Element1: 123123 \n Element2: 456456"

## compare to gsub, match every colon
gsub(":", "", x, fixed = TRUE)
# [1] "Request(123) \n Element1 123123 \n Element2 456456"

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

Replace first occurrence of the , in the string with regex

Maybe you could use ^([^,]+), and replace with $1.

This will capture from the beginning of the string ^ not a comma in a group ([^,]+) and then match a comma ,

How to replace first occurrence of string in Java

You can use replaceFirst(String regex, String replacement) method of String.



Related Topics



Leave a reply



Submit