-8

I am having a text as below

*~*****|****|**|*|***|***|****|**|null|null|**|***|***|null|71713470|STMS#****** 

using java i need to get the number 71713470 and STMS values from that string. I have tried all the string methods but invain. Could anyone help on this

Mallik
  • 679
  • 2
  • 14
  • 18
  • 2
    so ... use the split method, and take the 15th and 16th elements of the resulting array – Stultuske Aug 05 '16 at 06:40
  • If i split i am getting as individual element not as an whole text. For example String[] parts = string.split("|"); String part1 = parts[0]; String part2 = parts[1]; System.out.println(parts[2]); – Mallik Aug 05 '16 at 06:46
  • Hi fabian could you please provide me the regex pattern to get the text of that position – Mallik Aug 05 '16 at 06:48
  • @Malik since that is what you need, what's the problem? – Stultuske Aug 05 '16 at 06:49

2 Answers2

1

Use a Pattern with groups to get the relevant parts of the string:

Pattern p = Pattern.compile("\\|(\\d+)\\|STMS#(.*)$");

Matcher m = p.matcher("*~*****|****|**|*|***|***|****|**|null|null|**|***|***|null|71713470|STMS#******");
if (m.find()) {
    System.out.println(m.group(1));
    System.out.println(m.group(2));
}
fabian
  • 80,457
  • 12
  • 86
  • 114
  • mmm one doubt.... is not hardcoding `STMS` avoid any other text output? (i can imagine OP is not having only this string, but many in this weird format), if text are fixed, fix also number, if not a simple `substring` will do the job.... – Jordi Castilla Aug 05 '16 at 07:04
  • op want to extract STMS text itself as stated in comments: *but for STMS the content after that is also coming* – Jordi Castilla Aug 05 '16 at 07:13
  • and your code outputs `71713470` and `******` what does not make much sense..... – Jordi Castilla Aug 05 '16 at 07:16
0

NOTE: Actually technique fabian's using with Pattern and Matcher is far more correct and elegant, but code provided there is not returning values required by OP .


You can use String::split(String). It takes a regular expression to split, so use it, [] means containing one of... so putting | inside will match what you want:

String s = "*~*****|****|**|*|***|***|****|**|null|null|**|***|***|null|71713470|STMS#******";
s.split("[|]")[14]

Will output:

71713470

And

s.split("[|]")[15].split("[#]")[0]

Will give you

STMS
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109