本文介绍了Java:找到大写字母时拆分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是一个简单的问题,但我无法找到一个简单的解决方案(比如,少于10行代码:):

I think this is an easy question, but I am not able to find a simple solution (say, less than 10 lines of code :)

我有一个 String ,例如thisIsMyString,我需要将其转换为 String [] { this,Is,My,String}

I have a String such as "thisIsMyString" and I need to convert it to a String[] {"this", "Is", "My", "String"}.

请注意第一个字母不是大写字母。

Please notice the first letter is not uppercase.

推荐答案

你可以使用零宽度正向前瞻的正则表达式 - 它找到大写字母但不包括它们分隔符:

You may use a regexp with zero-width positive lookahead - it finds uppercase letters but doesn't include them into delimiter:

String s = "thisIsMyString";
String[] r = s.split("(?=\\p{Upper})");

Y(?= X)匹配 Y 后跟 X ,但不包括 X 成比赛。所以(?= \\\\ {Upper})匹配一个空序列后跟一个大写字母, split 将其用作分隔符。

Y(?=X) matches Y followed by X, but doesn't include X into match. So (?=\\p{Upper}) matches an empty sequence followed by a uppercase letter, and split uses it as a delimiter.

参见获取有关Java regexp语法的更多信息。

See javadoc for more info on Java regexp syntax.

编辑:顺便说一句,它也不适用于thisIsMyÜberString。对于非ASCII大写字母,您需要一个Unicode大写字符类而不是POSIX一个:

By the way, it doesn't work with thisIsMyÜberString too. For non-ASCII uppercase letters you need a Unicode uppercase character class instead of POSIX one:

String[] r = s.split("(?=\\p{Lu})");

这篇关于Java:找到大写字母时拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 11:22