Java 获取特定字符串后的所有内容
我有一个字符串作为Java 获取特定字符串后的所有内容,java,regex,split,Java,Regex,Split,我有一个字符串作为“process\u client\u 123\u Tree”和“process\u abc\u pqr\u client\u 123\u Tree”。我想提取“process\u client”和“process\u abc\u pqr\u client”之后的所有内容,并将其存储在字符串变量中 此处currentKey变量可以包含上述两个字符串中的任意一个 String clientId = // how to use currentKey here so that I c
“process\u client\u 123\u Tree”
和“process\u abc\u pqr\u client\u 123\u Tree”
。我想提取“process\u client”
和“process\u abc\u pqr\u 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
正则表达式分解:
^匹配行的开头流程(客户)匹配“流程”后接“客户”或“abc”pqr(客户)(捕获为第1组)
(.*)$表示任何字符,*表示0或更多次,因此它匹配字符串中的剩余字符,直到结束($),并将其捕获为组2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Matchit{
public static void main(String []args){
String str = "process_abc_pqr_client_123_Tree";
Pattern p = Pattern.compile("process_abc_pqr_client_(.*)|process_client_(.*)");
Matcher m = p.matcher("process_abc_pqr_client_123_Tree");
if (m.find( )) {
System.out.println("Found value: " + m.group(1) );
}
}
}
让你:
123_Tree
regexp中的括号定义了匹配组。管道是逻辑or。点表示任何字符,星表示任何数字。因此,我使用该regexp创建了一个模式对象,然后使用matcher对象来获取已匹配字符串的部分。regex模式可以是:
是零件(?:abc\U pqr)?
打开一个(?:
零次或一次)?
匹配一个或多个\w+
[A-Za-z0-9.]
组(1)
/中
要将其扩展到右侧,请匹配到正确的令牌
"process_(?:abc_pqr_)?client_(\\w+?)_trace_count"
其中
\w+?
匹配尽可能少的单词字符以满足条件。或者:-使用模式或使用startswith测试,然后使用substring该模式是什么样子的?我已经使用startswith
对上述两个字符串进行了if检查,我需要在if块内部执行此操作,使其看起来像这样我只能使用模式。请尝试String clientId=currentKey.replaceFirst(“进程。*客户端”,“”)
@saka129只要字符串的所需部分不包含另一个客户端
!*
贪婪并会吃掉字符串的其余部分,就可以了。瞧,解释@user1803551!谢谢,它工作得很好。如果我想提取这两个字符串过程之间的所有内容,正则表达式会是什么ss_client_
和_trace_count
在这个字符串中处理_client_123_Tree_trace_count
所以我想从这个字符串中提取123_Tree
。^process_client(.*)_trace_count$
——同样,您只有一个匹配的组。^process client_(..*u trace_count将是regex