Home > Java > javaTutorial > body text

How to split string in Java

WBOY
Release: 2023-04-26 22:55:13
forward
2364 people have browsed it

使用方法

split 方法的一种声明为,

public String[] split(String regex)
Copy after login

其中 regex 指的是正则表达式分隔符,我们平时使用单个字符作为分隔符,其实可以看作特殊的正则表达式,特殊之处在于这种表达式只匹配它自身,如 "-"  只匹配 "-", 示例如下:

String string = "86-15003455666"; String[] parts = string.split("-"); String part1 = parts[0]; // 86 String part2 = parts[1]; // 15003455666
Copy after login

split 方法的另一个声明为:

public String[] split(String regex, int limit)
Copy after login

regex 指的是 正则表达式分隔符,limit 指定的则是分割的份数,举个例子就明白了

String string = "004-556-42"; String[] parts = string.split("-", 2);   // 限定分割两份 String part1 = parts[0]; // 004 String part2 = parts[1]; // 556-42
Copy after login

而在某些场景下,我们可能想要在结果中保留分隔符,这也是可以做到了设置分隔符与分割后左侧的结果相连,

String string = "86-15003455666"; String[] parts = string.split("(?<p>设置分隔符与分割后右侧的结果相连,</p><pre class="brush:php;toolbar:false">String string = "86-15003455666"; String[] parts = string.split("(?=-)"); String part1 = parts[0]; // 86 String part2 = parts[1]; // -15003455666
Copy after login

机智的你可能已经发现了,其实分割方法的精妙之处,全在于正则表达式 regex 的设置,正则表达式还是要好好学习的!

妙用正则表达式

在实际的工作场景中,对于要分割的字符串,我们在分割之前,往往需要校验下它的格式,只有符合我们的要求,我们才对它进行拆分处理。而使用 Pattern 类加  Matcher 类,可以使字符串的格式识别和分割操作一气呵成:

public class SplitExample {     //\d代表数字,+代表出现一次或多次。所以(\\d+)-(\\d+)匹配用"-"相连的两个数字串     // Pattern 对象是正则表达式的编译表示     private static Pattern twopart = Pattern.compile("(\\d+)-(\\d+)");      public static void checkString(String s)     {         // Matcher对象对输入字符串进行解释和匹配操作         Matcher m = twopart.matcher(s);         if (m.matches()) {             //m.group(1) 和 m.group(2) 存储分割后的子串             System.out.println(s + " matches; first part is " + m.group(1) +                     ", second part is " + m.group(2) + ".");         } else {             System.out.println(s + " does not match.");         }     }      public static void main(String[] args) {         checkString("123-4567");  // 匹配         checkString("s-tar");    // 字母序列,不匹配         checkString("123-");    // "-"右侧的数字串为空,不匹配         checkString("-4567");    // "-"左侧的数字串为空,不匹配         checkString("123-4567-890");    // 存在两个"-",不匹配     } }
Copy after login

上述程序的运行结果为:

How to split string in Java

The above is the detailed content of How to split string in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!