"Here", "is", "an" "ex", "mple" 我尝试使用 String.sp-6ren">
gpt4 book ai didi

Java 字符串拆分为非字母字符

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:49:14 26 4
gpt4 key购买 nike

我想将一个字符串沿非字母字符拆分为一个字符串数组。例如:

"Here is an ex@mple" => "Here", "is", "an" "ex", "mple"

我尝试使用 String.split(String regex)使用正则表达式 "(?![\\p{Alpha}])" 的方法。然而,这会将字符串拆分为

"Here", "_is", "_an", "_ex", "@ample"

(那些下划线是为了强调有一个空格)。我猜这是因为 ?! 正则表达式运算符是“零宽度”的,实际上是拆分和删除输入字符串中非字母字符之前的零宽度字符。

如何在拆分字符串时删除实际的非字母字符?是否存在非零宽度否定运算符?

最佳答案

你可以尝试 \P{Alpha}+:

"Here is an ex@mple".split("\\P{Alpha}+")
["Here", "is", "an", "ex", "mple"]

\P{Alpha} matches any non-alphabetic character (as opposed to \p{Alpha}, which matches any alphabetic character). + indicates that we should split on any continuous string of such characters. For example:

"a!@#$%^&*b".split("\\P{Alpha}+")
["a", "b"]

关于Java 字符串拆分为非字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13714549/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com