0

Suppose i have this string : "X1 + X2 = Y3 + Y4 * Y5" , from this string i wanna get an array {X1,X2,Y3,Y4,Y5} My problem is how manage the following case : "X11 + X2 = Y3 + Y4 * Y5" , in this case i would get an array : {X1,X11,X2,Y3,Y4,Y5} and this is wrong because "X1" doesn't exist .

I didn't develop any algorithm yet , my idea was two declare two arrays with values from X1..XN and Y1..YN and for each value check if it is contained in my string , but in this way i will have a trouble explained above .

I would like to know how to do it , i would prefer not to use any external library to do this .

Frank
  • 873
  • 1
  • 7
  • 17
  • You can use split with multiple delimiters. [there](https://stackoverflow.com/questions/5993779/use-string-split-with-multiple-delimiters) is a case like yours. – Alex Samson Mar 13 '18 at 14:02
  • 1
    Your question should include all relevant details. You say that in your case you got wrong results, yet you don't explain how you got them. – M. Prokhorov Mar 13 '18 at 14:14

2 Answers2

2

You can use split with this regex \\P{Alnum}+ which split in any one or more non alphanumerical your solution can be :

String text = "X11 + X2 = Y3 + Y4 * Y5";
String[] split = text.split("\\P{Alnum}+");//This equivalent to "[^a-zA-Z\\d]+"

Outputs

[X11, X2, Y3, Y4, Y5]
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
1

My Own solution is :

String patternString = "[X|Y]{1}\\d+";

        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(text);

        while(matcher.find()) {
            System.out.println(text.substring(matcher.start(), matcher.end()));
        }

[X|Y]{1}\\d+ means X or Y letter which appear only once followed from any number of digits

Frank
  • 873
  • 1
  • 7
  • 17