[英]Java regex to split a string by using different delimiters
Suppose I want to split a string by either space character or the %20
string, how should I write my regex? 假设我想用空格字符或
%20
字符串拆分字符串,我该怎么写我的正则表达式?
I tried the following, but it didn't work. 我尝试了以下,但它没有用。
String regex = "[\\s+, %20]";
String str1 = "abc%20xyz";
String str2 = "abc xyz";
str1.split(regex);
str2.split(regex);
The regex doesn't seem to work on str1
. 正则表达式似乎不适用于
str1
。
use the alternation |
使用交替
|
: :
String regex = "(?:\\s+|%20)+";
String regex = "(\\s{1}+|%20{1}+)";
If you want to split by ONE space or ONE "%20", try this: 如果你想拆分一个空格或一个“%20”,试试这个:
String regex = "(\\s|%20)";
If you want to split by AT LEAST ONE space or AT LEAST ONE "%20", then try this: 如果你想分开至少一个空格或至少一个“%20”,那么试试这个:
String regex = "(\\s+|(%20)+)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.