如何使用正则表达式Java

时间:2019-07-16 20:50:29

标签: java regex count character matching

在给定的两个词中,是否可以使用正则表达式查找多个与字符以及索引匹配的字符串。

例如:

String1 = cat 
String2 = carrot

前两个字符和索引是匹配的(ca)。 t不计在内,因为它不在同一索引中。

我已经尝试过循环。但是,它似乎不起作用,效率也不高。

for (int i = 0; i < string1.length(); i++){
    for (int j = 0; j < string2.length(); j++){
        char ch1 = string1.charAt(i);
        char ch2 = string2.charAt(j);
        if (ch1 == ch2) {
            count char++;
    }
}

3 个答案:

答案 0 :(得分:0)

您可能需要的是最长的公共前缀

请参见Find longest common prefix?

正则表达式用于模式匹配。这是一个解决其他问题的方法。

答案 1 :(得分:0)

For循环仍可用于此作业,以查找每个字符串具有相同字符和发生次数的位置:

TicketingDocumentInfo doc = new TicketingDocumentInfo(new TicketingDocument(Collections.singletonList(new TicketingDocumentCoupon(4))));
List<TicketingDocumentInfo> docsToMatch = Arrays.asList(
        new TicketingDocumentInfo(new TicketingDocument(Collections.singletonList(new TicketingDocumentCoupon(2)))),
        new TicketingDocumentInfo(new TicketingDocument(Collections.singletonList(new TicketingDocumentCoupon(3)))),
        new TicketingDocumentInfo(new TicketingDocument(Collections.singletonList(new TicketingDocumentCoupon(4))))
);

Set<String> refsId = doc.getDocument().getCoupons().stream()
        .flatMap(c -> c.getRefsId().stream())
        .collect(Collectors.toSet());
Optional<TicketingDocumentInfo> result = docsToMatch.stream()
        .filter(d -> d.getDocument().getCoupons().stream()
                .flatMap(c -> c.getRefsId().stream())
                .anyMatch(refsId::contains))
        .findFirst();

答案 2 :(得分:0)

我猜您想计算两个单词在相同位置重复的字符数。 (前缀不同)

cat carrot一词,由于ca处于同一位置,而t不是,您想得到2。 >

carrot cabra一词,您将得到3,因为car(第4个)在相同位置相同。

您只需要同时在两个字符串上进行一次迭代:

String string1 = "car";
String string2 = "carrot";

int minLength = Math.min( string1.length(), string2.length() );

int count = 0;
for (int i = 0; i < minLength; i++){
    char ch1 = string1.charAt(i);
    char ch2 = string2.charAt(i);
    if (ch1 == ch2) {
        count++;
    }
}

我们使用minLength,因为我们只需要检查直到最小单词的长度即可。

我们要使用string1.charAt(i)string2.charAt(i),并使用相同的索引i,因为我们要检查相同位置的字符。