简体   繁体   English

用正则表达式分割字符串

[英]Split a string with regular expression

How can I split string for 3 character? 如何将字符串拆分为3个字符? (I don't want to do loop for this, maybe some regular expression will be help) (我不想为此循环,也许一些正则表达式会有所帮助)

I give example: 我举个例子:

String str = "111222333444";
String[] result = str.split("help?"); // get "111", "222", "333"

Using guava-library 使用番石榴库

 Iterable<String> strNums = Splitter.fixedLength(3).split("111222333444")

Readable than using regex. 比使用正则表达式可读。 You can then use Ints.tryParse(...) to get Integer version if you want. 然后,您可以根据需要使用Ints.tryParse(...)获取Integer版本。

Using .split will match regular expressions in the string which, in the underlying implementation, involves traversing the entire string anyway. 使用.split将匹配字符串中的正则表达式,在基础实现中,无论如何都要遍历整个字符串。 Writing a simple loop to just create a token from every 3 characters would probably be more efficient. 编写一个简单的循环以仅每3个字符创建一个令牌可能会更有效。

坦白说,我认为您不能针对没有循环的未定义长度的字符串执行此操作。

You can not use split because the arg of split is the separator, not the resulting sub-strings. 您不能使用split因为split的arg是分隔符,而不是结果的子字符串。 So, your separator regex would be nothing !? 因此,您的分隔符regex将nothing

Sorry, you heve write loop. 抱歉,您已经编写了循环。 BTW, the regex engine for split is full of loops. 顺便说一句,用于split的正则表达式引擎充满了循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM