-2

I have a string such as below:

String str="tile tile-2 tile-position-1-4"

I wish to receive the numbers in an array,such as [2,1,4].

My own solution is to break the string using split, but i am wondering if there is a shortcut using Regx

Thanks to @nitzien with Regx it tried:

String pattern= "^tile tile-(\\d*) tile-position-(\\d*)-(\\d*)$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
System.out.println(m.group(0));
System.out.println(m.group(1));
System.out.println(m.group(2));

But, it complains with:

java.lang.IllegalStateException: No match found
3
  • Will there be always three numbers in whole of string? Commented Sep 29, 2018 at 18:47
  • Yes, it is a pattern. Commented Sep 29, 2018 at 18:48
  • 1
    try this String[] result =Arrays.stream(str.split("\\D")).filter(s->!s.isEmpty()).toArray(String[]::new); Commented Sep 29, 2018 at 19:07

1 Answer 1

1
regex pattern - "^tile tile-(\d*) tile-position-(\d*)-(\d*)$"
replacement - "[\1,\2,\3]" 

Replacement is string which you will need to convert to array depending on which language you are using.

Updated answer after edited question

String str="tile tile-2 tile-position-1-4";
String pattern= "^tile tile-(\\d*) tile-position-(\\d*)-(\\d*)$";
System.out.println(str.replaceAll(pattern, "$1,$2,$3"));

This will give

2,1,4
Sign up to request clarification or add additional context in comments.

4 Comments

i have updated my question, do you have any idea?
What is classname in Matcher m = r.matcher(className);?
it is str sorry
Please check updated answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.