如何使用单个replaceAll查找Java中两个字符串共有的字符? [英] How do I find the characters common to two strings in Java using single replaceAll?

查看:83
本文介绍了如何使用单个replaceAll查找Java中两个字符串共有的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以假设我有:

String s = "1479K";
String t = "459LP";

我想回来

String commonChars = "49";

两个字符串之间的常用字符.

the common characters between the two strings.

很显然,可以使用以下标准循环进行操作:

Obviously it is possible to do with a standard loop like:

String commonChars = "";
for (i = 0; i < s.length; i++)
{
    char ch = s.charAt(i);
    if (t.indexOf(ch) != -1)
    {
        commonChars = commonChars + ch;
    }
}

但是,我希望能够使用replaceAll在一行中执行此操作.可以按照以下步骤进行操作:

However I would like to be able to do this in one line using replaceAll. This can be done as follows:

String commonChars = s.replaceAll("["+s.replaceAll("["+t+"]","")+"]","");

我的问题是:是否可以使用replaceAll的单次调用来做到这一点?正则表达式是什么?我想我必须使用某种先行方式,但是当我想到它时,我的大脑就会变得糊涂.

My question is: is it possible to do this using a single invocation of replaceAll? And what would be the regular expression? I presume I have to use some sort of lookahead, but my brain turns to mush when I even think about it.

推荐答案

String commonChars = s.replaceAll("[^"+t+"]","");

请注意,您可能需要在t中转义特殊字符,例如使用Pattern.quote(t)而不是上面的t.

Note that you may need to escape special characters in t, e.g. using Pattern.quote(t) instead of t above.

这篇关于如何使用单个replaceAll查找Java中两个字符串共有的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆