开发者

using regular expressions with java string.replace

I have two questions.

1:

String = xx yy **

I want to remove "xx " so String becomes = "yy *" (xx/yy is fixed and * can be anything) I tried something like this but it does not work:

string.r开发者_开发问答eplaceall("^(xx )$", "");

Isn't this supposed to replace the first occurence of "xx " with "" ?

SOLVED(by Lucas)

2:

String = xx yy **

I want to remove " yy **" so that String becomes = "xx" I thought something like this, but since the first doesnt work i suspoect this will not too.

string.replaceall("^( yy)*$", "");

UNSOLVED

I actually phrased this one insufficiently,

xx should be **

so xx is not fixed

** yy ** should become ** which is the first **


In both cases, you're using ^ and $ before and after what you're trying to replace. That tries to match the whole string with the bit that you want to remove. That's why it's not removing anything.

If you really only want to replace the first occurrence of xx, you should probably look at creating a Pattern, matching it against the text, and using Matcher.replaceFirst to perform the replacement.


Try this for the question1:

string.replaceFirst("^xx ", "");

for the second one:

string.replaceFirst(" yy .*$", "");

EDIT: if regex is not a must, we can use this for the second one:

string.substring(0, string.indexOf(" yy");

EDIT2: If '\n' will be included in the string, this works for the second one:

string.replaceFirst(" yy [\\w\\W]*$", "");
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜