[英]Splitting a string java
我有一个格式字符串:
<+923451234567>:您好,这里是文本。
现在,我想获取手机号(不包含任何非字母数字字符),即在<>符号之间的字符串开头的923451234567,以及文本,即Hi,这里是文本。
现在,我可以放置一个当前正在执行的硬编码逻辑。
String stringReceivedInSms="<+923451234567>: Hi here is the text.";
String[] splitted = cpaMessage.getText().split(">: ", 2);
String mobileNumber=MyUtils.removeNonDigitCharacters(splitted[0]);
String text=splitted[1];
如何从带有正则表达式的字符串中整齐地获取所需的字符串? 这样我就不必在字符串格式更改时就更改代码。
String stringReceivedInSms="<+923451234567>: Hi here is the text.";
Pattern pattern = Pattern.compile("<\\+?([0-9]+)>: (.*)");
Matcher matcher = pattern.matcher(stringReceivedInSms);
if(matcher.matches()) {
String phoneNumber = matcher.group(1);
String messageText = matcher.group(2);
}
使用匹配模式的正则表达式- <\\\\+?(\\\\d+)>: (.*)
使用Pattern
和Matcher
Java类来匹配输入字符串。
Pattern p = Pattern.compile("<\\+?(\\d+)>: (.*)");
Matcher m = p.matcher("<+923451234567>: Hi here is the text.");
if(m.matches())
{
System.out.println(m.group(1));
System.out.println(m.group(2));
}
您需要使用正则表达式,以下模式将起作用:
^<\\+?(\\d++)>:\\s*+(.++)$
这是您将如何使用它-
public static void main(String[] args) throws IOException {
final String s = "<+923451234567>: Hi here is the text.";
final Pattern pattern = Pattern.compile(""
+ "#start of line anchor\n"
+ "^\n"
+ "#literal <\n"
+ "<\n"
+ "#an optional +\n"
+ "\\+?\n"
+ "#match and grab at least one digit\n"
+ "(\\d++)\n"
+ "#literal >:\n"
+ ">:\n"
+ "#any amount of whitespace\n"
+ "\\s*+\n"
+ "#match and grap the rest of the string\n"
+ "(.++)\n"
+ "#end anchor\n"
+ "$", Pattern.COMMENTS);
final Matcher matcher = pattern.matcher(s);
if (matcher.matches()) {
System.out.println(matcher.group(1));
System.out.println(matcher.group(2));
}
}
我已经添加了Pattern.COMMENTS
标志,因此该代码将与嵌入的注释一起使用,以备将来参考。
输出:
923451234567
Hi here is the text.
您只需执行以下操作即可获取电话号码:
stringReceivedInSms.substring(stringReceivedInSms.indexOf("<+") + 2, stringReceivedInSms.indexOf(">"))
因此,请尝试以下代码段:
public static void main(String[] args){
String stringReceivedInSms="<+923451234567>: Hi here is the text.";
System.out.println(stringReceivedInSms.substring(stringReceivedInSms.indexOf("<+") + 2, stringReceivedInSms.indexOf(">")));
}
您不需要拆分字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.