Java – prefix a character before each word in string

I am looking for a function that prefixes a character before each identified word in a given string. Eg: when I pass a string “(var1 + var2-var3 + 30)%var4“, I must expect “($var1 + $var2-$var3 + 30)%$var4“. In the given string, only the words must be identified and ‘$‘ must be prefixed. All numbers, white spaces, operators (+, -, *, /, %) must be ignored.


OOTB, there does not exist any such function. You can define a function which would use a regex e.g. (?i)(?:[a-z_]w+) to identify variable words and replace them with $$0 where $0 refers to the match (the replaceable parameter) and $ before it is for prefixing $ to it.

Note: I am assuming the variable words may include an underscore (i.e. _). If not, use the RegEx pattern, (?i)(?:[a-z]p{Alnum}+). Note that w includes alphabets, digits and underscore.


public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(getString("(var1 + var2-var3 + 30)%var4"));

    static String getString(String str) {
        return str.replaceAll("(?i)(?:[a-z_]\w+)", "\$$0");


($var1 + $var2-$var3 + 30)%$var4

Explanation of the regex at regex101:

enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *