简体   繁体   English

如何拆分Java字符串但保留其部分内容?

[英]How to split Java String but preserve part of its' content?

I am working on java string split. 我正在研究java字符串拆分。 I wish to split the String according to ". uppercase"(There is a space between " . " and "uppercase"), for example: 我希望根据“ .uppercase”(“ . ”和“ uppercase”之间有一个空格)分割字符串,例如:

". A" ". B" ". C"...

Also, I wish to preserve the "." 另外,我希望保留“。” and the "uppercase", is there any efficient way to do that? 还有“大写字母”,有没有有效的方法呢? I use 我用

String.split("\\.\\s") 

before, but it will remove the "." 之前,但是它将删除“。” I use. 我用。 So that's not an ideal solution. 因此,这不是理想的解决方案。 Thanks 谢谢

Sample result 样品结果

String = This is an Egg. This is a dog. "I just come up with this example"
String[0] = This is an Egg.
String[1] = This is a dog. "I just come up with this example"

More edit: 更多编辑:

There is an issue that the usual way seems will preserve the delimiter at one of it's string. 有一个问题,通常的方法似乎会将定界符保留在它的一个字符串中。 but I wish to split the delimiter in some sense.(in my example, the ". [AZ]" is splited too) 但我希望在某种意义上拆分定界符。(在我的示例中,“。[AZ]”也已拆分)

You can use a lookaround : 您可以使用环顾四周

str.split("(?<=\\.\\s+)(?=\p{Lu})")

This will split "First sentence. Foo bar. test" into the array 这会将"First sentence. Foo bar. test"拆分为数组

{ "First sentence. ", 
  "Foo bar. test" }

If you don't want the space to be included, just put it between the lookaround assertions: 如果您不希望包含该空间,则将其放在环视断言之间:

str.split("(?<=\\.)\\s+(?=\p{Lu}")

This will result in 这将导致

{ "First sentence.", 
  "Foo bar. test" }

For the example string above. 对于上面的示例字符串。

Here You go: 干得好:

Use str.replaceAll(". ",".##"); 使用str.replaceAll(". ",".##");

str.replaceAll(".",".##");

Then use String.split("##") 然后使用String.split("##")

This will give you the required string. 这将为您提供所需的字符串。

Check this link 检查此链接

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

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