java - S1 包含带有正则表达式的 s2

标签 java regex

这是我的问题: 我有 2 个字符串 s1s2 作为输入,我需要找到 s2s1 中的初始位置。 s2 中有一个 * 字符,在正则表达式中代表 *+

示例:

s1: "abcabcqmapcab"
s2: "cq*pc"

输出应为:5

这是我的代码:

import java.util.*;

public class UsoAPIBis {

    /* I need to find the initial position of s2 in s1. 
    s2 contains a * that stands for any characters with any frequency. */

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("String1: ");
        String s1 = scan.next();
        System.out.print("String2: ");
        String s2 = scan.next();
        //it replace the star with the regex ".*" that means any char 0 or more more times.
        s2 = s2.replaceAll("\\*", ".*");
        System.out.printf("The starting position of %s in %s in %d", s2, s1, posContains);
    }

    //it has to return the index of the initial position of s2 in s1
    public static int indexContains(String s1, String s2) {
        if (s1.matches(".*"+s2+".*")) {
            //return index of the match;
        }
        else {
            return -1;
        }
    }
}

最佳答案

我认为你的意思是给定字符串中的 * 应该代表 .+.* 而不是 *+.正则表达式中的 . 字符表示“任何字符”,+ 表示“一次或多次”,* 表示“零次或多次” (贪婪地)。

在这种情况下,您可以使用:

public class Example {

    public static void main(String[] args) {

        String s1 = "abcabcqmapcab";
        String s2 = "cq*pc";

        String pattern = s2.replaceAll("\\*", ".+"); // or ".*"
        Matcher m = Pattern.compile(pattern).matcher(s1);
        if (m.find())
            System.out.println(m.start());
    }
}

输出:

5

关于java - S1 包含带有正则表达式的 s2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557668/

相关文章:

python - 如何检查字符串是否仅包含 “a-z” 、 “A-Z” 和 “0-9” 个字符

javascript Replace() 函数与正则表达式的奇怪行为

php - REGEX 永远不会与 .htaccess 中的 Origin 匹配

java - 如何使用 JDBC 检测 ENUM 字段的内容?

Java http-读取大文件

java - Hibernate 中按计数排序

python - 将隐含乘法 (*) 添加到 Python 字符串的最佳方法?

java - hibernate 一对多关系未正确更新

java - 当 TelephonyManager.EXTRA_STATE_RINGING 时从 BroadcastReceiver 刷新 RecyclerView

c++ - 链接到 gcc 中的 boost 正则表达式