简体   繁体   English

替换Java中的某些固定字符串

[英]Replacing certain fixed String in java

I have a string query which looks like this 我有一个看起来像这样的字符串查询

{"query":{"bool":{"should":[{"terms":{"user.id":[#users_to_follow],"minimum_match":1}},{"terms":{"tweets":[#keywords_to_track],"minimum_match":1}}]}},"filter":{"range":{"publishedDate":{"from":#Unix_timestamp}}},"size":#sizelength}" {“ query”:{“ bool”:{“ should”:[{“ terms”:{“ user.id”:[#users_to_follow],“ minimum_match”:1}},{“ terms”:{“ tweets” :[#keywords_to_track],“ minimum_match”:1}}]}},“ filter”:{“ range”:{“ publishedDate”:{“ from”:#Unix_timestamp}}},“ size”:#sizelength}“

I am trying to replace certain strings in the query with another string using: 我试图使用另一个字符串替换查询中的某些字符串:

query.replace("#users_to_follow",usersToFollow);
query.replace("#keywords_to_track", keyworsToTrack);
query.replace("#Unix_timestamp","1325930428000" );
query.replace("#sizelength",Integer.toString(SMLApplicationProperties.ES_RESULTSET_SIZE));

However when I run this thing, it does not actually replace the given strings from query. 但是,当我运行该程序时,它实际上并不会替换查询中给定的字符串。

You need to understand that String class is immutable. 您需要了解String类是不可变的。 Any operation on String returns a new String. 对String的任何操作都会返回一个新的String。 You need to assign it back to query variable: 您需要将其分配回查询变量:

query = query.replace("#users_to_follow",usersToFollow); 
query = query.replace("#keywords_to_track", keyworsToTrack); 
query = query.replace("#Unix_timestamp","1325930428000" ); 
query = query.replace("#sizelength",Integer.toString(SMLApplicationProperties.ES_RESULTSET_SIZE));

You need to get the result of the replace operation : 您需要获取replace操作的结果:

query = query.replace("#users_to_follow",usersToFollow);

That's because query.replace doesn't change the string you pass, it builds and returns a new one (string in java are immutable). 这是因为query.replace不会更改您传递的字符串,它会生成并返回一个新字符串(java中的字符串是不可变的)。

您可以优化(并非所有人都接受):

String query = query.replace("#users_to_follow",usersToFollow).replace("#keywords_to_track", keyworsToTrack).replace("#Unix_timestamp","1325930428000" ).replace("#sizelength",Integer.toString(SMLApplicationProperties.ES_RESULTSET_SIZE));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM