Remove a particular token from a string

2020-03-27 02:14发布

I have to remove a particular token from a String variable.

for eg: If the String variable is like "GUID+456709876790" I need to remove the "GUID+" part from the string and only need "456709876790".

How can it be done?

标签: java string
6条回答
啃猪蹄的小仙女
2楼-- · 2020-03-27 02:34

If you're using apache.commons.lang library you can use StringUtils just do:

StringUtils.remove(yourString, token);
查看更多
家丑人穷心不美
3楼-- · 2020-03-27 02:37

this works for me

String Line="test line 1234 abdc",aux;
token=new StringTokenizer(Line);

 while(token.hasMoreTokens())
   if(!("1234").equals(aux=token.nextToken())){ 
     new_line+= aux+" ";
     System.out.println("la nueva string es: "+ new_line);
   }
查看更多
Viruses.
4楼-- · 2020-03-27 02:39
String s = "GUID+456709876790";
String token = "GUID+";
s = s.substring(s.indexOf(token) + token.length());
// or s = s.replace(token, "");
查看更多
你好瞎i
5楼-- · 2020-03-27 02:45

Two options:

  • As you're just removing from the start, you can really easily use substring:

    text = text.substring(5);
    // Or possibly more clearly...
    text = text.substring("GUID+".length());
    
  • To remove it everywhere in the string, just use replace:

    text = text.replace("GUID+", "");
    

Note the use of String.replace() in the latter case, rather than String.replaceAll() - the latter uses regular expressions, which would affect the meaning of +.

查看更多
女痞
6楼-- · 2020-03-27 02:45

Just try this one :

String a = "GUID+456709876790";
String s = a.replaceAll("\\D","");

I am assuming that you want only digits as I have used regex here to remove any thing that is not a digit

查看更多
太酷不给撩
7楼-- · 2020-03-27 02:55
  String str = "GUID+456709876790"

 str.substring(str.indexOf("+")+1)
查看更多
登录 后发表回答