字符串间清除字符串

时间:2017-01-31 18:30:24

标签: java

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

if [[ "$(smartctl --log=selftest /dev/sda | awk 'NR>7 {print $4,$5,$6,$7}' | sed 's/offline//g; s/00%//g')" != *"Completed without error"* ]; then
   : ...put your error handling here...
fi

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

1 个答案:

答案 0 :(得分:2)

您可以将(.*my).*(is.*)replaceAll

一起使用

(.*my):捕获my之前的所有内容(.*my)$1代表<{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")); // 

演示

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);