Replace all odd occurrences of a substring using regex

regex match nth occurrence
regex replace nth occurrence
regex odd number of characters
regex ignore first occurrence
regular expression for odd number of as
regular expression for odd number of a's and b's
regular expression odd length
regex match second group

I have a string ~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~

I want to replace the odd occurrences of substring '~~' i.e 1st, 3rd.. with another string '**'.

My output should be **40~~ Celsius Temp: 33 Celsius Temp:**50~~

How to achieve this with regex in Java?

You really need a rudimentary parser to handle this; regex wasn't designed to count occurrences like this. The logic of the code below is simple. Every time we hit a match ~~ we do one of two things. If it is an odd occurrence, then we append empty string to the replacement, otherwise we reappend the ~~ which we matched.

String input = "~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~";
Pattern p = Pattern.compile("~~");
Matcher m = p.matcher(input);
StringBuffer sb = new StringBuffer(input.length());
int i = 0;

while (m.find()) {
    if (i % 2 == 0) {
        m.appendReplacement(sb, "**");
    }
    else {
        m.appendReplacement(sb, m.group(0));
    }
    ++i;
}
m.appendTail(sb);
System.out.println(sb.toString());

**40~~ Celsius Temp: 33 Celsius Temp:**50~~

Demo

Regex to replace every odd and even occurence in string , we replace every odd "_" occurence with "<em>". we replace every even "_" occurence with "</em>". I've been tinkering with String and Regex  Javascript replace() method replaces only the first occurrence of the string. To replace all occurrences of a string in Javascript, use the below methods. Javascript string replace method with regular expression. Javascript split and join method.

I think for your problem statement, you no need to search for odd occurrences , from the example it shows, you need to replace ~~(digit) with **(digit) and ignore other formats of ~~ ..

Advanced Regex: Find and Replace Every Second Instance Of A , Using regex, we can identify back ticks by writing /`/g . This small line will match every instance of a back tick in our string. back tick followed by 0 or more instances of any character other than a By adding `; after our $1 we are effectively replacing everything after and including our first back tick with itself  This simple regex will do the task: String.replace(/<TERM>/g, '') This performs a case sensitive substitution. Here is an example, where I substitute all occurrences of the word ‘dog’ in the string phrase: const phrase = 'I love my dog! Dogs are great' const stripped = phrase.replace(/dog/g, '') stripped //"I love my !

Well some have already suggested similar solution but still:

String org = "~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~";
String rep = org.replaceAll("~~(\\d)","**$1");

Here, ~~(\d) will search for ~~ followed by digit and replace with **, to preserve the first digit, using $1

Find substrings that contain all vowels python, If a regular expression string includes a backslash, you should tell Python not to have a checkbox that let you use regular expressions to find and replace text. in a haystack" problem by using the indexOf method to find all occurrences of a a dictionary with maximum value; Find the product of all odd, even numbers in​  REPLACE ALL OCCURRENCES OF REGEX working fine for me, check the below mentioned piece of code . Its giving desired output. Better you can check your Data declaration of your variable wa_var1. If its not resolved , kindly paste your code here. Try to fix the actual bug. Data : var type string value 'a_b_c_'.

You can use replacement of a capturing group, iff the ~~ come strictly in pairs.

private final static Pattern pattern = Pattern.compile("(?:~~([^~]+~~))");

public static String replaceOddTildes(String value) {
    return pattern.matcher(test).replaceAll("**$1");
}

And:

String result = replaceOddTildes("~~40~~ Celsius Temp: 33 Celsius Temp:~~50~~"));

Note that it will miss the last odd set of tildes if they are not in matching pairs:

replaceOddTildes("An ~~un~~ paired ~~example!").equals("An **un~~ paired ~~example!")`

If that's how you want an unmatched pair handled, of course, then that's fine.

The pattern in detail:

(?:             a non-capturing group, consisting of
    ~~          a pair of tildes, followed by
    (           a capturing group, consisting of
    [^~]+       one or more characters that is not a tilde, followed by
    ~~          a pair of tildes
    )           end of the capturing group
)               end of the non-capturing group

The replacement for the match is a pair of asterisks followed by the contents of the capturing group.

Count of occurrences of a "1(0+)1" pattern in a string, Given an alphanumeric string, find the number of times a pattern 1(0+)1 occurs in of a character in a string · Replace all occurrences of string AB with C without  The REPLACE () function returns a new string in which all occurrences of the substring. are replaced by the new_substring. It returns NULL if any argument is NULL. SQL Server REPLACE () function examples. Let’s take some examples of using the REPLACE () function to understand how it works. A) Using REPLACE () function with literal strings.

Replace all occurrences of string AB with C without using extra , Replace all occurrences of string AB with C without using extra space · Longest of odd elements is equal to sum of even elements · Count all sub-strings with weight of How to validate time in 12-hour format using Regular Expression · Program to print a Given a string str that may contain one more occurrences of “​AB”. In the following example we are using replaceAll() method to replace all the occurrences of a given substring with the new string. The difference between replace() and replaceAll() method is that the replace() method replaces all the occurrences of old char with new char while replaceAll() method replaces all the occurrences of old string with

replace every character at odd index with "&" in a string · GitHub, class Nes. {. public static void main(String[] args) {. String a = "lastavice trče";. for (​int i=0; i < a.length(); i++){. if (i % 2 != 0){. a = a.substring(0,i-1) + "&" +  The .replace() method can actually accommodate replacing all occurrences; however, the search string must be replaced with a regular expression. A regular expression — regex for short — is an

Replace every odd or even occurrence of a pattern in a file, This Java String tutorial explains how to work with Java Strings. Matching a String Against a Regular Expression With matches() Strings With trim(); Replacing Characters in Strings With replace(). replaceFirst(); replaceAll() also has a lastIndexOf() method which finds the last occurrence of a substring. An empty substring in regex is not a valid regular expression and raises an exception. A character string is empty if regex is either an empty string or is of type c, n, d, or t and only contains blanks. Some regular expressions that are not empty, such as a*, are used to search for empty character strings.

Comments
  • This is a very strange use of regex. Strongly consider using something like a loop to do this instead. (Not all tasks can be accomplished using regex.)
  • Is it guaranteed that there will always be an even number of them? Is it okay if it fails, or misses the last one, if they don't come in pairs?
  • You should replace it with "**" to match OP's requirement, but there's no real need for counting occurrences if only pairs need to be replaced.
  • @DavidConrad I disagree with your logic, because who says that we will always have pairs of ~~. The actual replacement logic we want here is in fact to iterate through, replacing all odd occurrences, with or without a pair, so...
  • Since OP hasn't specified, it is unclear what OP would like to have done with a mismatched pair. It seems just as likely to me that it is considered illegal and ought to be ignored. Until OP clarifies, nothing more can be said.
  • Would the downvoter care to explain or suggest improvements?