Replace one character in a match via Regex

I have a simple template that I am trying to find and replace. He must replace all dashes with periods when they are surrounded by numbers.

Replace the period in them:

3-54
32-11
111-4523mhz

Like so:

3.54
32.11
111.4523mhz

However, I do not want to replace the dash inside anything like this:

Example-One
A-Test

I tried using the following:

preg_replace('/[0-9](-)[0-9]/', '.', $string);

However, this will replace the entire match, not just the middle. How do you replace only part of a match?

+5
source share
4 answers
preg_replace('/([0-9])-([0-9])/', '$1.$2', $string);

Gotta do the trick :)

Edit: A few more explanations:

Using (and )in regex, you create a group. This group can be used in replacement. $1replaced by the first agreed group, $2replaced by the second agreed group, etc.

, (,) '$1.$2' '$2.$1', . , , , .

+9

regex , :

preg_replace('/(?<=[0-9])-(?=[0-9])/', '.', $string);
+1

You can use backlinks to save the parts of the match that you want to keep:

preg_replace('/([0-9])-([0-9])/', '$1.$2', $string);
0
source

Below are a few ways to achieve the same.

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Rituraj_Jain on 7/14/2017.
 */
public class Main {

    private static final Pattern pattern = Pattern.compile("(\\S)-(\\S)");
    private static final String input = "Test-TestBad-ManRituRaj-Jain";

    public static void main(String[] args) {
        Matcher matcher = pattern.matcher(input);
        String s = matcher.replaceAll("$1 $2");
        System.out.println(s);

        System.out.println(input.replaceAll(pattern.pattern(), "$1 $2"));


    }
    public static void main1(String[] args) {
        Matcher matcher = pattern.matcher(input);
        StringBuffer finalString = new StringBuffer();
        while(matcher.find()){
            String replace = matcher.group().replace("-", " ");
            matcher.appendReplacement(finalString, replace);
        }
        matcher.appendTail(finalString);
        System.out.println(input);
        System.out.println(finalString.toString());
    }
}

-1
source

All Articles