Regex 替换预定义字符范围之前的所有内容 – Java

huangapple go评论67阅读模式
英文:

Regex replacing everything before a predefined range of chars - Java

问题

我有一些字符串值,我想删除或替换掉"TV|TH"之前的所有内容。我的问题是,尽管使用了正确的语法,字符串似乎保持不变。

String test = "10TH";
String replaceBeforeSide = test.replaceAll("^(TH|TV)+", "");
System.out.println(replaceBeforeSide);
//期望结果 = "TH";
英文:

I have string values where I want to remove or replace everything that comes before "TV|TH". My problem is that despite using the correct syntax, the string seems to stay the same.

 String test = "10TH";
 String replaceBeforeSide =  test.replaceAll("^\\(TH|TV)+", "");
 System.out.println(replaceBeforeSide);

//Desired result = "TH";

答案1

得分: 2

Sure, here is the translated code portion:

将我的评论转换为答案,以便将来的访问者可以轻松找到解决方案。

您可以使用一个简单的正则表达式与一个捕获组:

replaceBeforeSide = test.replaceAll(".+?(TH|TV)", "$1");

或者更简短的:

replaceBeforeSide = test.replaceAll(".+?(T[HV])", "$1");

使用`.+?`,我们匹配1个或多个任何字符(非贪婪),然后匹配并捕获在第1组中的`(TH|TV)`。在替换中,我们只需放置`$1`,以便仅删除`(TH|TV)`之前的字符串。

我们还可以使用前瞻而避免捕获组:

replaceBeforeSide = test.replaceAll(".+?(?=T[HV])", "");

如果要忽略大小写,请使用内联修饰符`(?i)`:

replaceBeforeSide = test.replaceAll("(?i).+?(?=T[HV])", "");
英文:

Converting my comment to answer so that solution is easy to find for future visitors.

You could use a simple regex with a capture group:

replaceBeforeSide = test.replaceAll(".+?(TH|TV)", "$1");

or even shorter:

replaceBeforeSide = test.replaceAll(".+?(T[HV])", "$1");

Using .+?, we are matching 1+ of any character (non-greedy) before matching (TH|TV) that we capture in group #1.

In replacement we just put $1 back so that only string before (TH|TV) is removed.

We could also use a lookahead and avoid capture group:

replaceBeforeSide = test.replaceAll(".+?(?=T[HV])", "");

If you want to match ignore case then use inline modifier (?i):

replaceBeforeSide = test.replaceAll("(?i).+?(?=T[HV])", "");

huangapple
  • 本文由 发表于 2020年8月10日 17:20:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63337410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定