我有一个字符串作为 "process_client_123_Tree"
和 "process_abc_pqr_client_123_Tree"
。我想提取 "process_client_"
和 "process_abc_pqr_client_"
之后的所有内容,并将其存储在一个字符串变量中。
这里的currentKey
变量可以包含以上两个字符串中的任何一个。
String clientId = // how to use currentKey here so that I can get remaining portion in this variable
正确的做法是什么?我应该只在这里使用 split 还是一些正则表达式?
最佳答案
import java.util.regex.*;
class test
{
public static void main(String args[])
{
Pattern pattern=Pattern.compile("^process_(client_|abc_pqr_client_)(.*)$");
Matcher matcher = pattern.matcher("process_client_123_Tree");
while(matcher.find())
System.out.println("String 1 Group 2: "+matcher.group(2));
matcher = pattern.matcher("process_abc_pqr_client_123_Tree");
while(matcher.find())
System.out.println("String 2 Group 2: "+matcher.group(2));
System.out.println("Another way..");
System.out.println("String 1 Group 2: "+"process_client_123_Tree".replace("process_client_", ""));
System.out.println("String 2 Group 2: "+"process_abc_pqr_client_123_Tree".replace("process_abc_pqr_client_", ""));
}
}
输出:
$ java test
String 1 Group 2: 123_Tree
String 2 Group 2: 123_Tree
Another way..
String 1 Group 2: 123_Tree
String 2 Group 2: 123_Tree
正则表达式分解:
^ 匹配行首
process_(client_|abc_pqr_client_) 匹配“process_”后跟“client_”或 abc_pqr_client_”(捕获为第 1 组)
(.*)$ 。表示任何字符和 * 表示 0 次或多次,因此它匹配字符串中的其余字符直到结束 ($) 并将其捕获为第 2 组
关于java - 获取特定字符串后的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35591137/