[英]how do i remove first and last occurrence of the sentence in java
I have a following line : |A|B|C|D|100|E|GEN|smsplus|11|11|11|
我有以下一行:
|A|B|C|D|100|E|GEN|smsplus|11|11|11|
and I want to remove the first and last occurrence of |
我想删除的首次和最后出现
|
. 。
I have to check first if the |
我必须先检查
|
is available at first and last
first and last
可用
I am sure that this will bring me some down votes but really don't know how to go about. 我相信这会使我有些反对,但真的不知道该怎么做。
EDIT 编辑
I also have to check for the following : 我还必须检查以下内容:
A|B|C|D|100|E|GEN|smsplus|11|11|11| and |A|B|C|D|100|E|GEN|smsplus|11|11|11 and there is no
possibilities for ||
||
可能性 that is why I did not want to give any explanation for the same. 这就是为什么我不想对此作任何解释。
thanks for your valuable time. 感谢您的宝贵时间。
You can perhaps use the regex: 您也许可以使用正则表达式:
^\\|(.*)\\|$
And replace by $1
: 并替换为
$1
:
If the start and end of the string are not both |
如果字符串的开头和结尾都不都是
|
, there'll be no replacement. ,将无法替代。
EDIT: As per your last comment, if you want to remove the |
编辑:根据您的最后评论,如果要删除
|
if it's either at the start and/or at the end of the string, then use an OR operator (there's too many |
in that question I think =P): 如果它在字符串的开头和/或结尾,则使用OR运算符(该问题中有太多
|
我认为= P):
^\\||\\|$
Replace by nothing (empty string ""
) 请勿替换(空字符串
""
)
EDIT2: 编辑2:
If the first regex is closer to what you need but also want to remove multiple pipes, add quantifiers: 如果第一个正则表达式更接近您的需要,但又想删除多个管道,则添加量词:
^\\|+(.*)\\|+$
If the second regex (in first edit) is what you need but also want to remove multiple pipes, add quantifiers again! 如果您需要第二个正则表达式(在第一次编辑中),但又想删除多个管道,请再次添加量词!
^\\|+|\\|+$
Note that the replacement strings remain the same in both cases 请注意,两种情况下的替换字符串均保持不变
Your comments lead me to believe that you want to do this: 您的评论使我相信您想这样做:
String result = subject.replaceAll("^\\||\\|$", "");
This will change each of the following strings: 这将更改以下每个字符串:
|A|B|C|
|A|B|C
A|B|C|
A|B|C
to the same string A|B|C
. 到相同的字符串
A|B|C
See it on regex101.com . 在regex101.com上查看 。
Use indexOf()
and lastIndexOf()
from java.lang.String
package 使用
java.lang.String
包中的indexOf()
和lastIndexOf()
String s="|A|B|C|D|100|E|GEN|smsplus|11|11|11|";
s=s.substring(s.indexOf("|"),s.lastIndexOf("|"));
System.out.println(s); //Prints A|B|C|D|100|E|GEN|smsplus|11|11|11
Try, 尝试,
String input = "|A|B|C|D|100|E|GEN|smsplus|11|11|11|";
input = input.substring(1, input.length()-1);
or use StringUtils.removeStart, removeEnd 或使用StringUtils.removeStart,removeEnd
StringUtils.removeStart(input, "|");
StringUtils.removeEnd(input, "|");
or 要么
StringUtils.strip(input, "|");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.