gpt4 book ai didi

java - 在子字符串上使用 "Predefined character classes"

转载 作者:行者123 更新时间:2023-12-01 19:08:49 24 4
gpt4 key购买 nike

我想使用 '\W' 检查字符串的最后一个字符是否为非单词字符,并允许使用某些符号,例如“.,!等”,我想到使用代码与此类似。

Boolean notCompleted = true;
int deduct = 1;
while(notCompleted){
if(string.charAt(string.length() -deduct) == '\W'){ // '\W' <-- doesn't work since it accepts anything other than "escape sequences".
if(string.charAt(string.length() -deduct) == '.'||string.charAt(string.length() -deduct) == ','||string.charAt(string.length() -deduct) == '!'){
//Do nothing and move on to the while loop
}else{
//Replace the non word character with ' '.
}
}
deduct++;
if(deduct >= html.length()){
notCompleted = false;
}
}

这不起作用的原因是因为使用 string.charAt 只接受“转义序列”。

My question is there another way to pull this off rather than doing.

string.replaceAll("\W", "");

非常感谢所有建议。谢谢。

感谢 npinti 给我的提示,我构建了这段代码。但是我收到一条错误行

所请求的 fakeNewString 的期望结果应该是“!asdsdefwef.,a,,sda.sd”;

fakeNewString = sb.toString(); // NullPointerException

public static void test5(){
Boolean notCompleted = true;
String fakeNewString = "!@#$%^&*( asdsdefwef.,a,,sda.sd";
int start = 0, end = 1;
StringBuilder sb = null;
try{

while(notCompleted){
start++;
String tempString = fakeNewString.substring(start, end);
if(Pattern.matches("\\W$", tempString)){
if(Pattern.matches("!", tempString)||Pattern.matches(".", tempString)||Pattern.matches(",", tempString)||Pattern.matches("\"", tempString)){
//do nothing
sb.append(tempString);
}else{
//Change it to spaces.
tempString = " ";
sb.append(tempString);
}
}
end++;
if(end >= fakeNewString.length()){
notCompleted = false;
fakeNewString = sb.toString();
System.out.println(fakeNewString);
}
}

}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}

最佳答案

你可以这样做:

Pattern pattern = Pattern.compile("\\W$");
Matcher matcher = pattern.match(string);

if (matcher.find())
{
//do something when the string ends with a non word character
}

看看this有关正则表达式的更多信息的教程。

关于java - 在子字符串上使用 "Predefined character classes",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9081192/

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