简体   繁体   English

有关Java正则表达式的问题

[英]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: 我目前正在使用此reg表达式从我的文本文件中删除此类术语:

   myString = myString.replaceAll("[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" 它应该变成: "blabla cococo pppoooo"

But it doesn't work 但这不起作用

thanks 谢谢

You need to assign the return value of replaceAll back to the string reference: 您需要将replaceAll的返回值分配回字符串引用:

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. 我想保留=然后从上面的reg exp字符串中删除。

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. codeaddict的答案可以正确满足您的要求,但是它将保留由于删除内容而导致的多余空间。 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM