Java string replace placeholder

First, Java text placeholder replacement

My needs are texting, there is a newline in it.
I am very packaged here, you can define according to your needs.

1. Code actual combat

(1). Template enumeration

 /** * @ProductName: IntelliJ IDEA * @ProjectName: tangerine_util * @Description: * @Witticism: Your ability to learn and experience in solving problems will always be the only thing holding you back * @User: Tangerine * @Email: [email protected] | [email protected] * @Date: 2021/9/13 21:42 Monday * @version: V1.0.0 */ public class Enums   public enum SmsTemplate   VIEW("Hello:? \ N Congratulations, your trial is:?", 2), TEST("I am &, you are &, he is &.", 3); String content; Integer paramSize; SmsTemplate(String content, Integer paramSize)   this.content = content; this.paramSize = paramSize; > public String getContent()   return content; > public void setContent(String content)   this.content = content; > public Integer getParamSize()   return paramSize; > public void setParamSize(Integer paramSize)   this.paramSize = paramSize; > > > 

(2). Packaging tool

 import com.tangerine.enums.Enums; import java.util.Arrays; import java.util.List; import java.util.function.BiFunction; import java.util.stream.Collectors; /** * @ProductName: IntelliJ IDEA * @ProjectName: hr-homa-service * @Description: SMS content tool replacement template parameters . * @Witticism: Your ability to learn and experience in solving problems will always be the only thing holding you back * @User: Tangerine * @Email: [email protected] | [email protected] * @Date: 2021/8/24 15:08 Tuesday * @version: V1.0.0 */ public class SmsContentUtil   / ** Default replacement number placeholder * / public static final String replace(Enums.SmsTemplate template, ListString> params)   return replace(template, "?", params); > / ** ourselves the placeholder * / public static final String replace(Enums.SmsTemplate template, String symbol, ListString> params)   /** * @Description: Replace the in the SMS content string in the template to Params * @Auther: tangerine * @Email: [email protected] and [email protected] * @Date: 2021/8/25 0:55 * @Param Template SMS template enumeration class * @Param Symbol placeholder * @Param Params internal because there is a REMOVE operation, so avoid arrays.aslist () operations * @return: java.lang.String * @Exception: RuntimeException If the number of parameters corresponding to the parameter and template do not match, throw an exception */ return execute(template.getContent(), template.getParamSize(), (ct, ps) ->   if (!(ps == params.size())) throw new RuntimeException("The number of parameters does not match"); return Arrays.asList(ct.split("")).stream().map(e -> e.equals(symbol) ? params.remove(0) : e).collect(Collectors.joining()); >); > private static final String execute(String content, Integer paramSize, BiFunctionString, Integer, String> bf)   return bf.apply(content, paramSize); > > 

(3). Use tutorial

The programmer who does not look at the comment is not necessarily a bad programmer, but it is definitely not a good programmer . hahaha

 @Test public void testSmsTemplate()  / / Must be optimistic about my comment System.out.println("------------------ Do not transfer placeholder, default replacement number ------------------"); String replace1 = SmsContentUtil.replace(Enums.SmsTemplate.VIEW, new ArrayListString>()    // I am a little low for simplicity, write it. add("Ouyang Wenyan"); add("100001"); >>); System.out.println(replace1); System.out.println("------------------ Transfer placeholder, specify replacement placeholder ------------------"); String replace2 = SmsContentUtil.replace(Enums.SmsTemplate.TEST, "&", new ArrayListString>()    // I am a little low for simplicity, write it. add("Ouyang Wenyan"); add("Ouyang Na"); add("Ouyang Yuhan"); >>); System.out.println(replace2); //1.smscontentutil.replace This method has an overload, and if not transferred symbols, then automatically replace the question mark (?), // 2. The paramsize inside must be equal to the transmission list. Xize, not unanimous, no problem > 

(4). Output results

------------------Do not transfer placeholders, default replacement number-------------------- Hello: Ouyang Wenyan Congratulations, your trial is successful,Your temporary number is:100001------------------Pass placeholders, specify replacement placeholders-------------------- I am Ouyang Wenyan,You are Ouyang Na Na,He is Ouyang Yuhan. 

Источник

Replacing Placeholder Variables in a String

I think for such a simple task you don’t need to use RegEx:

$variables = array("first_name"=>"John","last_name"=>"Smith","status"=>"won");
$string = 'Dear , we wanted to tell you that you the competition.';

foreach($variables as $key => $value) $string = str_replace('', $value, $string);
>

echo $string; // Dear John Smith, we wanted to tell you that you won the competition.

how to replace a placeholder in a string?

You can use place-holders and str_replace . Or use PHP’s built-in sprintf and use %s . (And as of v4.0.6 you can swap the ordering of arguments if you’d like).

$name = 'Alica';

// sprintf method:
$format = 'Hello, %s!';
echo sprintf($format, $name); // Hello, Alica!

// replace method:
$format = "Hello, !";
echo str_replace("", $name, $format);

And, for anyone wondering, I understood that is trouble templating a string, not PHP’s integrated concatenation/parsing. I just assume keep this answer up though as I’m still not 100% sure this OP’s intent

Java Is there a feature for replacing placeholders inside a String with a String variable

JDK 7+ has String.format() which I what I think you’re looking for

replace placeholders in string

If you receive your string in a variable you should do interpolation by yourself

To do so, you need to find all placeholders and replace they value. You can do this with regular expression (can be simplified if placeholder can start with digits)

Next method will do this replacement:

public static string Replace(string input, Dictionary replacement)
var regex = new Regex("<(?[a-z_][a-z0-9_]*?)>",
RegexOptions.Compiled | RegexOptions.IgnoreCase);

return regex.Replace(input, m =>
var key = m.Groups["placeholder"].Value;
if (replacement.TryGetValue(key, out var value))
return value.ToString();

throw new Exception($"Unknown key ");
>);
>
var input = "Insert into Emp(Id,Name,Number,Address) values(,\"Abc\",,);";
var replaces = new Dictionary
,
< "Number", 55668878>,
,
>;

var result = Replace(input, replaces);
Console.WriteLine(result);

Insert into Emp(Id,Name,Number,Address) values(123,»Abc»,55668878,»test address»);

String interpolation in Typescript, replacing ‘placeholders’ with variables

Use a template string which are much better than String.Format in my opinion as they do not suffer from poor indexing (wrong placeholder) issues:

var text = "blah blah";
var strTest = `This is a $`;
console.log(strTest);

Twig: Replace placeholder in string with include

You have to do it in two steps, first capture the partial in a variable, then use the variable to replace the placeholder, e.g.

note: is used to strip whitespaces

Replace placeholders in string stored in a text file with variables

Meta-character \b matches a zero-width boundary between a word-class character and a non-word class character.

< and >are not word-class characters. So your pattern doesn’t work.

Remove \b or replace it to \s .

Replace placeholders with dynamic data in strings with php

$string = '[1] edited profile picture of [2]';

$replaceArray = array('[1]' => 'Mark Zuckerberg',
'[2]' => 'John doe');

$string = strtr($sting, $replaceArray);
echo $string;
?>
Mark Zuckerberg edited profile picture of John doe

format string in oracle SQL to replace placeholders with variable names given at the end of the string

I am assuming that the last comma is the delimiter between the template string and the delimited terms. You can use a recursive sub-query factoring clause and simple string functions:

WITH terms ( value, terms, num_terms ) AS ( 
SELECT SUBSTR( value, 1, INSTR( value, ', ', -1 ) - 1 ),
SUBSTR( value, INSTR( value, ', ', -1 ) + 2 ),
REGEXP_COUNT(
SUBSTR( value, INSTR( value, ', ', -1 ) + 2 ),
'.+?(\| |$)'
)
FROM table_name
),
term_bounds ( rn, value, terms, start_pos, lvl ) AS (
SELECT ROWNUM,
REPLACE(
value,
'%' || num_terms,
CASE num_terms
WHEN 1
THEN terms
ELSE SUBSTR( terms, INSTR( terms, '| ', 1, num_terms - 1 ) + 2 )
END
),
terms,
CASE
WHEN num_terms > 1
THEN INSTR( terms, '| ', 1, num_terms - 1 )
ELSE 1
END,
num_terms
FROM terms
UNION ALL
SELECT rn,
REPLACE(
value,
'%' || (lvl - 1),
CASE lvl - 1
WHEN 1
THEN SUBSTR( terms, 1, start_pos - 1 )
ELSE SUBSTR(
terms,
INSTR( terms, '| ', 1, lvl - 2 ) + 2,
start_pos - INSTR( terms, '| ', 1, lvl - 2 ) - 2
)
END
),
terms,
CASE
WHEN lvl > 2
THEN INSTR( terms, '| ', 1, lvl - 2 )
ELSE 1
END,
lvl - 1
FROM term_bounds
WHERE lvl > 1
)
SEARCH DEPTH FIRST BY rn SET rn_order
SELECT value
FROM term_bounds
WHERE lvl = 1;

Which, for the sample data:

CREATE TABLE table_name ( value ) AS
SELECT '%1||'-'||%2||%3, SITE_NO| SITE_NAME| COUNTRY' FROM DUAL UNION ALL
SELECT '0.1 * %1, WIND_RES' FROM DUAL UNION ALL
SELECT '%1, TOTAL' FROM DUAL UNION ALL
SELECT 'CASE WHEN LENGTH(%1) < 8 THEN NULL ELSE TO_DATE(%1,'yyyymmdd')END, MIN_DATE' FROM DUAL UNION ALL
SELECT '%1(+)=%3 and %2(+)=%4, ABC| LMN| PQR| XYZ' FROM DUAL UNION ALL
SELECT '%1, %2, %3, %4, %5, %6, %7, %8, %9, %10, %11, ONE| TWO| THREE| FOUR| FIVE| SIX| SEVEN| EIGHT| NINE| TEN| ELEVEN' FROM DUAL UNION ALL
SELECT '%%%%%%%7, HELLO| 1| 2| 3| 4| 5| 6' FROM DUAL

| VALUE |
| :—————————————————————————————— |
| SITE_NO||’-‘||SITE_NAME||COUNTRY |
| 0.1 * WIND_RES |
| TOTAL |
| CASE WHEN LENGTH(MIN_DATE) < 8 THEN NULL ELSE TO_DATE(MIN_DATE,'yyyymmdd')END |
| ABC(+)=PQR and LMN(+)=XYZ |
| ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN |
| HELLO |

CREATE FUNCTION substitute_values( 
i_value IN VARCHAR2,
i_terms IN VARCHAR2,
i_term_delimiter IN VARCHAR2 DEFAULT '| '
) RETURN VARCHAR2 DETERMINISTIC
IS
TYPE term_list_type IS TABLE OF VARCHAR2(200);
v_start PLS_INTEGER := 1;
v_end PLS_INTEGER;
v_index PLS_INTEGER;
v_terms term_list_type := term_list_type();
v_output VARCHAR2(4000) := i_value;
BEGIN
LOOP
v_end := INSTR(i_terms, i_term_delimiter, v_start);
v_terms.EXTEND;
IF v_end > 0 THEN
v_terms(v_terms.COUNT) := SUBSTR(i_terms, v_start, v_end - v_start);
ELSE
v_terms(v_terms.COUNT) := SUBSTR(i_terms, v_start);
EXIT;
END IF;
v_start := v_end + LENGTH(i_term_delimiter);
END LOOP;

LOOP
v_index := TO_NUMBER(REGEXP_SUBSTR(v_output, '^(.*?)%(\d+)', 1, 1, NULL, 2));
IF v_index IS NULL THEN
RETURN v_output;
ELSIF v_index > v_terms.COUNT THEN
RETURN NULL;
END IF;
v_output := REGEXP_REPLACE(v_output, '^(.*?)%(\d+)', '\1' || v_terms(v_index));
END LOOP;
END;
/
SELECT SUBSTITUTE_VALUES( 
SUBSTR(value, 1, INSTR(value, ', ', -1) - 1),
SUBSTR(value, INSTR(value, ', ', -1) + 2)
) AS value
FROM table_name

VALUE
SITE_NO||’-‘||SITE_NAME||COUNTRY
0.1 * WIND_RES
TOTAL
CASE WHEN LENGTH(MIN_DATE) < 8 THEN NULL ELSE TO_DATE(MIN_DATE,'yyyymmdd')END
ABC(+)=PQR and LMN(+)=XYZ
ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, ELEVEN
HELLO

Источник

Java String Replace placeholders in a string by the values of the map structure.

Replace placeholders in a string by the values of the map structure.

  • format The string to be formatted
  • values The key/value map for the replacement of the placeholders

the formatted string

//package com.java2s; import java.util.ArrayList; import java.util.Map; import java.util.Map.Entry; public class Main < /**// w w w. d e m o 2 s . c o m * Replace placeholders in a string by the values of the map structure. * * @param format The string to be formatted * @param values The key/value map for the replacement of the placeholders * @return the formatted string * @author: http://stackoverflow.com/a/2295004/794395 */ public static String dictFormat(String format, MapString, Object> values) < StringBuilder convFormat = new StringBuilder(format); ArrayList valueList = new ArrayList(); int currentPos = 1; for (EntryString, Object> entry : values.entrySet()) < String key = entry.getKey(), formatKey = "%(" + key + ")", formatPos = "%" + Integer.toString(currentPos) + "$s"; int index = -1; while ((index = convFormat.indexOf(formatKey, index)) != -1) < convFormat.replace(index, index + formatKey.length(), formatPos); index += formatPos.length(); >valueList.add(entry.getValue()); currentPos++; > System.out.println(convFormat.toString()); return String.format(convFormat.toString(), valueList.toArray()); > >

  • Java String Replace all instances of search string with the replace string.
  • Java String Replace all occurrences of the following characters [&, ] with their corresponding entities.
  • Java String Replace any occurrences of either a percentile (%) or underscore (_) with the replacement string
  • Java String Replace placeholders in a string by the values of the map structure.
  • Java String replace single quotes with \’
  • Java String Replaces a string tokenized using tokenizeNewline(String str) with the original string.
  • Java String Replaces all occurences of space with its escape-sequence «%20».

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Читайте также:  Compare function in cpp
Оцените статью