如何从ArrayList中筛选字符串的部分内容

huangapple 未分类评论50阅读模式
英文:

How to filter parts of a string from an arraylist

问题

我有一个 ArrayList<String> listWithoutDuplicates,其中存储着如下元素:

[java.security.AlgorithmParameters.getInstance( alg);, java.security.AlgorithmParameters.getInstance( alg _);, java.security.AlgorithmParameters.init( params);, java.security.AlgorithmParameters.init( parAr);, java.security.AlgorithmParameters.init( parAr _);, parsRes = java.security.AlgorithmParameters.getEncoded();, parsRes = java.security.AlgorithmParameters.getEncoded( format);]

我尝试提取以下输出,并将其存储在另一个 List 中:

getInstance( alg) 
getInstance( alg _)
init( params)
init( parAr)
init( parAr _)
getEncoded()
getEncoded( format)

我试图用 , 替换 .,现在我想要获取每个部分,在分号 ; 之前。

String sat = listWithoutDuplicates.toString().replace(".", ",");
List<String> answer = Arrays.asList(sat.split(";")); 

有人能帮我处理一下吗?
最好的问候。

英文:

I have an ArrayList&lt;String&gt; listWithoutDuplicates which stores the elements like this:

[java.security.AlgorithmParameters.getInstance( alg);, java.security.AlgorithmParameters.getInstance( alg _);, java.security.AlgorithmParameters.init( params);, java.security.AlgorithmParameters.init( parAr);, java.security.AlgorithmParameters.init( parAr _);, parsRes = java.security.AlgorithmParameters.getEncoded();, parsRes = java.security.AlgorithmParameters.getEncoded( format);]

I'm trying to extract the following output and store this in another List:

getInstance( alg) 
getInstance( alg _)
init( params)
init( parAr)
init( parAr _)
getEncoded()
getEncoded( format)

I tried to use the replace the . with , and now I'm trying to get every part which is before ;.

String sat = listWithoutDuplicates.toString().replace(&quot;.&quot;, &quot;,&quot;);
List&lt;String&gt; answer = Arrays.asList(sat.split(&quot;;&quot;)); 

Could somebody please help me with this.
Best regards.

答案1

得分: 0

str.replaceAll("(.*);", "$1");

这会得到分号之前的所有内容(注意这是在单个字符串上操作,不是在数组中的每个字符串上操作)。

这利用了正则表达式的分组属性。如果你不了解正则表达式,我强烈建议你阅读一些教程并尝试一下。(注意:不同的实现略有不同,所以你需要先了解其背后的原则,然后随着学习逐渐掌握每种实现(语言/框架)的“语法糖”)。

英文:

str.replaceAll(&quot;(.*);&quot;, &quot;$1&quot;); 

should get you everything before the ; (note this is on a single string, not each str in the array)

This makes use of the grouping property of regex (regular expression). If you don't know regex, then I HIGHLY recommend you go read some tutorials and try it out. (note: most different implementations are slightly different, so you'll have to learn the principles behind it and then learn the 'syntax sugar' of each implementation (which language/framework) as you go.)

huangapple
  • 本文由 发表于 2020年5月4日 23:40:34
  • 转载请务必保留本文链接:https://java.coder-hub.com/61596071.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定