[Java] Split string (Java)

2 minute read

Introduction

I tried to summarize various patterns of character division.

Pattern with one delimiter and no second argument

public class Sample {
	public static void main(String[] args) {
		String str = "1,2,3,4";
		String[] strs = str.split(",");
		for (String num : strs) {
			System.out.println(num);
		}
		System.out.println("Number of arrays:"+strs.length);
	}
}

Execution result.


1
2
3
4
Number of arrays:4

Pattern with one delimiter and second argument (when the second argument is greater than 0)

public class Sample {
	public static void main(String[] args) {
		String str = "1,2,3,4";
		String[] strs = str.split(",",3);
		for (String num : strs) {
			System.out.println(num);
		}
		System.out.println("Number of arrays:"+strs.length);
	}
}

Execution result.


1
2
3,4
Number of arrays:3

The second argument specifies the number of elements.
In this case, 3 is specified, so the number of elements is 3.

Pattern with one delimiter and second argument (when the second argument is a negative value)

public class Sample {
	public static void main(String[] args) {
		String str = "1,2,3,4,";
		String[] strs = str.split(",",-1);
		for (String num : strs) {
			System.out.println(num);
		}
		System.out.println("Number of arrays:"+strs.length);
	}
}

Execution result.


1
2
3
4

Number of arrays:5

When the second argument is negative, the number of elements in the array is not limited and the empty string at the end of the array is not deleted.
In this case, -1 was specified, but the number of elements is not limited because it is a negative value. It also contains an empty string.

When there are multiple delimiters

public class Sample {
	public static void main(String[] args) {
		String str = "1+2=3";
		String[] strs = str.split("[=+]");
		for (String num : strs) {
			System.out.println(num);
		}
		System.out.println("Number of arrays:"+strs.length);
	}
}

Execution result.


1
2
3
Number of arrays:3

To specify multiple delimiters, enter the delimiter in [].

When separating including the delimiter

public class Sample {
	public static void main(String[] args) {
		String str = "1,2,3";
		String[] strs = str.split("(?<=,)");
		for (String num : strs) {
			System.out.println(num);
		}
		System.out.println("Number of arrays:"+strs.length);
	}
}

Execution result.


1,
2,
3
Number of arrays:3

Use (? <=) To include the delimiter.

When separating including multiple delimiters

public class Sample {
	public static void main(String[] args) {
		String str = "1,2a3";
		String[] strs = str.split("(?<=[,a])");
		for (String num : strs) {
			System.out.println(num);
		}
		System.out.println("Number of arrays:"+strs.length);
	}
}

Execution result.


1,
2a
3
Number of arrays:3

To include multiple delimiters, enter the delimiter in [] of (? <= []).

Tags:

Updated: