Sco*_*aum 0 javascript java regex
如果您使用的是Java或JavaScript,那么有一种很好的方法可以执行String减法操作,以便给出两个字符串:
org.company.project.component
org.company.project.component.sub_component
Run Code Online (Sandbox Code Playgroud)
你得到:
sub_component
Run Code Online (Sandbox Code Playgroud)
我知道我可以编写代码来比较字符的字符串,但我希望有一种方法可以以非常紧凑的方式完成.
另一个用例是找到字符串之间的差异:
org.company.project.component.diff
org.company.project.component.sub_component
Run Code Online (Sandbox Code Playgroud)
我实际上只想删除相同的部分.
取决于正是你想要的.如果你正在寻找一种方法来比较一般情况下的字符串 - 意味着找到任意输入之间的公共子字符串 - 那么你正在寻找更接近Levenshtein距离和类似算法的东西.但是,如果你只需要前缀/后缀比较,这应该工作:
public static String sub(String a, String b) {
if (b.startsWith(a)) {
return b.subString(a.length());
}
if (b.endsWith(a)) {
return b.subString(0, b.length() - a.length());
}
return "";
}
Run Code Online (Sandbox Code Playgroud)
...或者大致相应的东西.
String result = "org.company.project.component.sub_component".replace("org.company.project.component","")
Run Code Online (Sandbox Code Playgroud)
应该管用...
编辑:Apache commons库也很好用
如下所述,StringUtils类实际上有一个方法: StringUtils.remove()
| 归档时间: |
|
| 查看次数: |
7273 次 |
| 最近记录: |