开发者

Question about regular expressions in Java

I'm parsing a text file and I need to remove all terms such this:

upcoming:event=103499
abc:dfe=123813
...

Format: `term1:term=0000000`

I'm currently using this reg expression to remove such terms from my text file:

   myString = myString.replac开发者_如何学CeAll("[0-9A-Za-z]+:[0-9A-Za-z]+", "");

So for example, if I have a string like this:

"blabla abc:dfe=123813 cococo ghi:pol=09339 pppoooo"

it should become: "blabla cococo pppoooo"

But it doesn't work

thanks


You need to assign the return value of replaceAll back to the string reference:

myString = myString.replaceAll("[0-9A-Za-z]+:[0-9A-Za-z]+", "");

And it works

But if you want to replace the entire string you can do:

myString = myString.replaceAll("[0-9A-Za-z]+:[0-9A-Za-z=]+", "");

EDIT:

For the edited question you can use:

myString = myString.replaceAll("[0-9A-Za-z]+:[0-9A-Za-z]+=[0-9]+ ?", "");

See it


Try:

myString=myString.replaceAll("[0-9A-Za-z]+:[0-9A-Za-z]+=", "");

I you would like to keep = then remove from the reg exp string above.


The answer by codeaddict works correctly to meet your requirements, with the exception that it will maintain the extra spaces caused by the removal of the content. The following logic removes the spaces as well:

String myString = "blabla abc:dfe=123813 cococo ghi:pol=09339 pppoooo";
// assumes that the string does not start with ' '
myString = myString.replaceAll("[0-9A-Za-z]+:[0-9A-Za-z=]+\\ ?", "");
// myString is now equal to "blabla cococo pppoooo" as per your edit.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜