[英]Java delete first part of string (case-insensitive)
I searched and couldn't find the right code as I only saw case sensitive ones. 我进行搜索,但找不到正确的代码,因为我只看到区分大小写的代码。
I am writing code that checks that the file name starts with "CMF-". 我正在编写代码,以检查文件名以“ CMF-”开头。 I have the code that if the name doesn't start with CMF- then it is added (this works). 我有代码,如果名称不是以CMF开头的,则将其添加(此方法有效)。
However, I am having an issue with case-sensitivity. 但是,我对区分大小写有疑问。 The first if statement is where I need help. 第一个if语句是我需要帮助的地方。
For example, when someone saves the name as cmf-something then I need to delete the cmf- and put CMF- in its place. 例如,当有人将名称另存为cmf-something时,我需要删除cmf-并将其放置在CMF-中。 As another example, someone saves a file as Cmf-something it will also need to delete the Cmf- and put CMF- in its place. 再举一个例子,有人将文件另存为Cmf,还需要删除Cmf-并将其放置在CMF中。
String name = document.getObjectName();
String newName;
String haystack = "CMF-";
if(haystack.regionMatches(true, 0, name, 0, 4) && !name.startsWith(haystack))
{
//part to delete lowercase cmf and then add cmf
}
//Check the object name for CMF-
if(!haystack.regionMatches(true, 0, name, 0, 4))
{
//System.out.println("Missing CMF- on name \nAdding CMF- to " + name);
StringBuffer str = new StringBuffer("CMF-");
newName = str.append(name).toString();
document.setObjectName(newName);
}
If I understand your question correct, just make it lowercase and check 如果我正确理解您的问题,请将其小写并检查
if(newString.toLowerCase().starstWith("cmf")){
newString = newString.substring(3);
}
Your approach seems overly complicated. 您的方法似乎过于复杂。 Why not do something like: 为什么不做这样的事情:
String name = document.getObjectName();
//Check for names starting "CMF-", "cmf-", "Cmf-", etc.
if (name.substring(0,4).equalsIgnoreCase("CMF-")){
name = "CMF-"+name.substring(4); //May even overwrite correct name.
} else {
name = "CMF-" + name;
}
And you can also include some error checking for names that would be too short and cause out of bounds exceptions. 而且,您还可以包括一些错误检查,以检查名称是否太短并导致超出范围的异常。
I like Lars Nielsen solution for it's simplicity, but if you would like to see how regular expression will look in such case, here it is: 我很喜欢Lars Nielsen解决方案,因为它很简单,但是如果您想了解在这种情况下正则表达式的外观,则为:
"Cmf-abc".matches("(?i)^cmf-.*"); // true
Regular expression (?i)^cmf-.*
works like this: 正则表达式(?i)^cmf-.*
工作方式如下:
(?i)
enables case insensitive-matching (by default it is case-sensitive). (?i)
启用不区分大小写的匹配(默认情况下,区分大小写)。 ^cmf-
means that we want to have cmf-
(or Cmf-
, CMF-
, ...) in the beggining of the string... ^cmf-
表示我们希望在字符串的Cmf-
包含cmf-
(或Cmf-
, CMF-
,...)。 .*
- ...followed with whatever. .*
-...紧随其后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.