Java从字符串中提取部分的最佳方法 [英] Java Best way to extract parts from a string
本文介绍了Java从字符串中提取部分的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字符串;
[Username [rank] -> me] message
等级,用户名和消息的字符每次都不同.将其分为三个独立变量(用户名,排名和消息)的最佳方法是什么?
The characters of the rank, username, and message will vary each time. What is the best way I can break this into three separate variables (Username, rank and message)?
我已经尝试过:
String[] parts = text.split("] ");
但是它会抛出错误.预先感谢!
But it is throwing back errors. Thanks in advance!
推荐答案
使用Java对正则表达式的支持( java.util.regex
),并使正则表达式匹配这三个部分.
Use Java's support for regular expressions (java.util.regex
) and let a regex match the 3 parts.
例如,这一个: ^ \ [([[ww] +)\ [([\ w] +)\]->->\ w + \](.*)$
Java代码段,略微改编自Ian F. Darwin的"Java Cookbook"(O'Reilly):
Java code snippet, slightly adapted from Ian F. Darwin's "Java Cookbook" (O'Reilly):
import java.util.regex.*;
class Test
{
public static void main(String[] args)
{
String pat = "^\\[([\\w]+) \\[([\\w]+)\\] -> \\w+\\] (.*)$";
Pattern rx = Pattern.compile(pat);
String text = "[Username [rank] -> me] message";
Matcher m = rx.matcher(text);
if(m.find())
{
System.out.println("Match found:");
for(int i=0; i<=m.groupCount(); i++)
{
System.out.println(" Group " + i + ": " + m.group(i));
}
}
}
}
输出:
Match found:
Group 0: [Username [rank] -> me] message
Group 1: Username
Group 2: rank
Group 3: message
这篇关于Java从字符串中提取部分的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文