用java拆分字符串
我有两种类型的字符串用java拆分字符串,java,regex,string,indexof,Java,Regex,String,Indexof,我有两种类型的字符串 command1|Destination-IP|DestinationPort Command2|Destination-IP|DestinationPort|SourceIP|SourcePort|message 我试图拆分字符串以获取变量 我开始这样编码,但不确定这是否是最好的方式 public String dstIp=""; public String dstPort=""; public String srcIp=""; public S
command1|Destination-IP|DestinationPort
Command2|Destination-IP|DestinationPort|SourceIP|SourcePort|message
我试图拆分字符串以获取变量
我开始这样编码,但不确定这是否是最好的方式
public String dstIp="";
public String dstPort="";
public String srcIp="";
public String scrPort="";
public String message="";
public String command="";
int first = sentence.indexOf ("|");
if (first > 0)
{
int second = sentence.indexOf("|", first + 1);
int third = sentence.indexOf("|", second + 1);
command = sentence.substring(0,first);
dstIp= sentence.substring(first+1,second);
dstPort= sentence.substring(second+1,third);
我可以这样继续吗?或者使用正则表达式?
如果字符串是
command1|Destination-IP|DestinationPort
我得到一个错误,因为没有第三个
|
最好在这里按管道符号分割输入:
String[] tokens = sentence.split( "[|]" ); // or sentence.split( "\\|" )
然后通过检查
tokens.length
来检查代币的#个数,并相应地采取行动 使用Java函数split(),它可以精确地管理您要查找的内容
示例代码:
String test = "bla|blo|bli";
String[] result = test.split("\\|");
将
split
与\\\\\124;
一起用作参数。它返回一个字符串[]
,该字符串将包含|拆分字符串的不同部分 看看这个方法:
旁注:由于“|”
字符在正则表达式中有特殊含义(基本上是“|”
的意思是或),因此应使用反斜杠将其转义
事实上,查看未scaped版本“first | second | third”.split(“|”)的结果非常有趣
正则表达式“|”
翻译成英文为“空字符串或空字符串”,并在任意位置匹配字符串“first | second | third”.split(“|”)返回一个长度为19的数组:{”、“f”、“i”、“r”、…、“d”}
myStr.split(\\\\\”)代码>或myStr.split(模式引号(“|”)
。您也可以使用apache commons中的一种方法,例如StringUtils.split(句子“|”)
No,|
应该转义。您还可以使用搜索功能:请参阅
String line = "first|second|third";
String[] splitted = line.split("\\|");
for (String part: splitted) {
System.out.println(part);
}