首页 \ 问答 \ 如何替换字符串中的多个子字符串实例(How to replace multiple instances of substring within a string)

如何替换字符串中的多个子字符串实例(How to replace multiple instances of substring within a string)

我需要在同一个地方替换不同内容的大字符串的一些内容。

可以说我有一个字符串:

String str = "package blah.foo.bar;\n"
           + "import org.blah.blah;\n"
           + "import sel.this.that;\n"
           + "import sel.boo.foo;\n"
           + "...more text";

我想将单词gen插入以import sel.开头的语句中import sel. 所以最终结果如下: import sel.gen.this.that;

我已经成功使用以下方法,但只有当我知道子字符串将在字符串中的位置时。 我的问题是,我不确定如何使以下代码动态:

private String modifyString(String str){
    String hold = str.substring(0, str.indexOf(";"));
    hold = new StringBuilder(hold).insert(13, "gen.").toString();
    str = str.replace("(?m)^package.*", hold);
    return str;

}

上面的代码正确地替换了字符串package blah.foo.bar;package blah.gen.foo.bar;

但这又一次只能替换字符串的开头部分。 我希望能够保存子字符串的所有实例,然后在这些子字符串中插入子字符串。


I need to replace some of the contents of a large string with different content in the same spot.

Lets say I have a string:

String str = "package blah.foo.bar;\n"
           + "import org.blah.blah;\n"
           + "import sel.this.that;\n"
           + "import sel.boo.foo;\n"
           + "...more text";

I want to insert the word gen into statements which start with import sel. So that the end result looks like: import sel.gen.this.that;

I have had success with the following method but only when I KNOW where that substring will be within the string. My issue is that I'm not sure how to make the following code dynamic:

private String modifyString(String str){
    String hold = str.substring(0, str.indexOf(";"));
    hold = new StringBuilder(hold).insert(13, "gen.").toString();
    str = str.replace("(?m)^package.*", hold);
    return str;

}

The above code correctly replaces the strings package blah.foo.bar; with package blah.gen.foo.bar;

But again this only works with replacing the beginning portion of the string. I'm looking to be able to hold all instances of a substring and then insert a substring within those substrings.


原文:https://stackoverflow.com/questions/34344616
更新时间:2022-06-07 20:06

最满意答案

您必须同时使用GROUP BY区域和lang,如下所示:

SELECT COUNT(*) as `count`,`region`, `lang`, DATE(NOW()) as `week_ending` 
FROM mydata.table 
WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND `date` < DATE(NOW()) 
GROUP BY `region`, `lang`, DATE(NOW());

You would have to GROUP BY both region and lang, like this:

SELECT COUNT(*) as `count`,`region`, `lang`, DATE(NOW()) as `week_ending` 
FROM mydata.table 
WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND `date` < DATE(NOW()) 
GROUP BY `region`, `lang`, DATE(NOW());

相关问答

更多
  • 您必须同时使用GROUP BY区域和lang,如下所示: SELECT COUNT(*) as `count`,`region`, `lang`, DATE(NOW()) as `week_ending` FROM mydata.table WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND `date` < DATE(NOW()) GROUP BY `region`, `lang`, DATE(NOW()); You would h ...
  • 查询中的问题是过滤后的别名的范围:从其他子查询中看不到它。 如果你真的想拥有它,你可以创建一个视图: create view filtered as SELECT * FROM push_message_info WHERE DATE(submit_date) > '2017-05-14'; SELECT p.pending, s.success, t.total FROM (SELECT count(*) AS pending FROM filtered WHERE served < total ...
  • 在这些情况下,你通常可以替换if a then b else c与(a AND b) OR ((NOT a) AND c) ,如下所示: SELECT * FROM Orders WHERE (Ordertype='confidential' AND ReqUser='$UserID') OR (Ordertype<>'confidential' AND ODep) ; 或者,根据您的数据,这可能也有效: SELECT * FROM Orders WHERE ReqUser='$UserID ...
  • 假设变量$genre和$model已经转义。 仅限演示代码,为清晰起见无安全性。 $sqlQuery = 'select * from games where 1=1'; if ( !empty($genre) ) $sqlQuery .= " and genre=$genre"; if ( !empty($model) ) $sqlQuery .= " and model=$model"; assuming variables $genre and $model already escaped. dem ...
  • 你需要转义斜杠(\)。 在mysql中,斜杠(\)用于转义类似查询中的字符。 Select * from User where username NOT LIKE 'Abc\\\\%' You need to escape slash (\). In mysql slash (\) is used to escape characters in a like query. Select * from User where username NOT LIKE 'Abc\\\\%'
  • 这应该做你需要的: $var1 = '1'; $var2 = '0'; $var3 = '1'; $where = array('1 = 1'); foreach (array('var1', 'var2', 'var3') as $var) { if ('1' == $$var) { $where[] = "$var = '1'"; } } // SELECT * FROM table WHERE 1 = 1 AND var1 = '1' AND var3 = '1' e ...
  • 您可以采用不同的方法 首先请求clientId = 3的每个用户; select u.id from users u INNER JOIN users_clients uc ON u.userID = uc.userID WHERE uc.clientID =3; 然后您可以使用此请求来获取除clientId = 3之外的所有用户。 最终请求如下所示: select u.id from users u where u.id NOT IN (select u.id from users u INNER J ...
  • 尝试这个: SELECT id, chapter_id, question, answer FROM (SELECT IF(@chapterId=@chapterId:=chapter_id, @id:=@id+1, @id:=0) queNo, id, chapter_id, question, answer FROM `questions`, (SELECT @chapterId:=0, @id:=0) AS A WHERE `chapter_id` IN (19, 20, ...
  • 如果你需要至少有一个过滤器的GID SELECT DISTINCT `gid` FROM `links` WHERE `filter_id` IN (1,2,3) 如果你需要GID,它有所有过滤器1,2,3 SELECT `gid` FROM `links` WHERE `filter_id` IN (1,2,3) GROUP BY `gid` HAVING COUNT( DISTINCT `filter_id`)=3 其中COUNT( DISTINCT filter_id )=3表示所有3个过滤 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)