search
HomeJavajavaTutorialHow to split string in Java

使用方法

split 方法的一种声明为,

public String[] split(String regex)

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

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

split 方法的另一个声明为:

public String[] split(String regex, int limit)

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

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

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

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

机智的你可能已经发现了,其实分割方法的精妙之处,全在于正则表达式 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");    // 存在两个"-",不匹配     } }

上述程序的运行结果为:

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment