[英]Trim unwanted characters in a Java String
I have few Java Strings like below: 我有一些如下的Java字符串:
ab-android-regression-4.4-git
ab-ios-regression-4.4-git
ab-tablet-regression-4.4-git
However, I do not want such lengthy and unwanted names and so I want to get rid of starting ab-
and ending -git
part. 但是,我不想这样冗长和多余的名称,因此我想摆脱开头
ab-
和结尾-git
部分。 The pattern for all the Strings is the same (starts with ab and ends with git) 所有字符串的模式都相同(以ab开始,以git结束)
Is there a function/class in Java that will help me in trimming such things? Java中是否有一个函数/类可以帮助我简化此类工作? For example, something like:
例如,类似:
String test = "ab-android-regression-4.4-git";
test.trim(ab, git)
Also, can StringUtils
class help me with this? 另外,
StringUtils
类可以帮助我吗? Thoughts on regular expressions? 对正则表达式有想法吗?
EDITED PART: I also want to know how to eliminate the -
characters in the Strings and change everything to uppercase letters 编辑部分:我也想知道如何消除字符串中的
-
字符并将所有内容更改为大写字母
Here's a method that's more general purpose to remove a prefix and suffix from a string: 这是从字符串中删除前缀和后缀的更通用的方法:
public static String trim (String str, String prefix, String suffix)
{
int indexOfLast = str.lastIndexOf(suffix);
// Note: you will want to do some error checking here
// in case the suffix does not occur in the passed in String
str = str.substring(0, indexOfLast);
return str.replaceFirst(prefix, "");
}
Usage: 用法:
String test = "ab-android-regression-4.4-git";
String trim = trim(test, "ab-", "-git"));
To remove the "-" and make uppercase, then just do: 要删除“-”并大写,请执行以下操作:
trim = trim.replaceAll("-", " ").toUpperCase();
由于要修剪的部分的大小是恒定的,因此您应该简单地使用substring:
yourString.substring(3, yourString.length - 4)
You can use test = test.replace("ab-", "")
and similar for the "-git"
or you can use test = StringUtils.removeStart(test, "ab-")
and similarly, removeEnd
. 您可以将
test = test.replace("ab-", "")
和类似的"-git"
用于"-git"
,也可以使用test = StringUtils.removeStart(test, "ab-")
以及类似地, removeEnd
。
I prefer the latter if you can use StringUtils
because it won't ever accidentally remove the middle of the filename if those expressions are matched. 如果可以使用
StringUtils
我更喜欢后者,因为如果匹配了这些表达式,它绝不会意外删除文件名的中间部分。
If your string always contains ab- at the begining and -git at the end then here is the code 如果您的字符串始终在开头包含ab-,在末尾包含-git,则代码如下
String test = "ab-android-regression-4.4-git";
test=test.substring(3, s.length() - 4);
System.out.println("s is"+s); //output is android-regression-4.4
To know more about substrings click https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html 要了解有关子字符串的更多信息,请单击https://docs.oracle.com/javase/tutorial/java/data/manipstrings.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.