0

I'm trying to remove something from a string that looks like:

"name" : "12345"

it will always be that 12345 can be any number, is there a way to do this with something like:

string.replace("\"name\":\"[0-9]\",", "")

that doesn't work, and i've tried several things but nothing works.

thank you!

5
  • please explain what "doesn't work" mean? What happens and what do you expect to happen? Commented Sep 20, 2017 at 12:47
  • Are you assigning the result of string.replace to another variable (or back to string; or printing it)? Commented Sep 20, 2017 at 12:48
  • can you please post what have you tried? Commented Sep 20, 2017 at 12:48
  • 1
    Use replaceAll, not replace. The former matches regexes; the latter matches the exact string. Commented Sep 20, 2017 at 12:48
  • string = string.replaceAll("\"name\":\"[0-9]\",", "") Commented Sep 20, 2017 at 12:49

4 Answers 4

2

Add a + behind the number part in order for the regex to match numbers of any length. [0-9] alone will only match exactly 1 digit.

Furthermore, what about spaces? In your example there are spaces, in your code, there are none. You can add \\s* to match any (including none) white-space.

string.replaceAll("\"name\"\\s*:\\s*\"[0-9]+\",", "")

You can play around with it on Regex101.

Andy Turner's comment: You need to use replaceAll instead of replace. replace does not interpret the first parameter as a regex, but tries to find that exact string in your string.

Sign up to request clarification or add additional context in comments.

Comments

1

this will do it for you

string.replaceAll( "\"name\"\\s*:\\s*\"\\d+\"", "" ) 

example:

final String string = "Some\"name\" : \"12345\"String";
System.out.println( string.replaceAll( "\"name\"\\s:\\s\"\\d+\"", "" ) 

will print the output:

SomeString

And it will work for any number

Comments

0

Replace "\"name\":\"[0-9]\" To "\"name\" : \"[0-9]*\""

Comments

0

I tried a regex like this

String regex="\\w+:\\d+";
        String data = "name:12345";
        System.out.println(data.matches(regex));

and output is true, you can try around this. \w+ matches one or more word characters and \d+ matches one or more numbers

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.