有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java清除字符串之间的字符串

例如,我有这样一个字符串:

String myString = "Hello my name is Skypit"

如何清除“我的”和“是”之间的所有内容? “我的”和“是”永远不会改变,但两者之间的一切都会改变。 所以这个例子的结果应该是“Hello myis Skypit”


共 (1) 个答案

  1. # 1 楼答案

    您可以将(.*my).*(is.*)replaceAll一起使用

    (.*my):捕获所有内容,直到my,其中(.*my)$1表示

    (is.*):捕获从is到结尾的所有内容,其中(is.*)$2表示

        String myString = "Hello my name is Skypit";
        System.out.println(myString.replaceAll("(.*my).*(is.*)", "$1$2"));
    
        // get the value in s
        // String s = myString.replaceAll("(.*my).*(is.*)", "$1$2");
    

    输出:

    Hello myis Skypit
    

    获取myis之间的内容

    System.out.println(myString.replaceAll(".*my(.*)is.*", "$1")); // 
    

    演示

    &13; 第13部分,;
    const regex = /(.*my).*(is.*)/g;
    const regex2 = /.*my(.*)is.*/g;
    const str = `Hello my name is Skypit`;
    const result = str.replace(regex, `$1$2`);
    const result2 = str.replace(regex2, `$1`);
    console.log('Output 1 : ',result);
    console.log('Output 2 : ',result2);
    和#13;
    和#13;