0

Here's the string format I'm working with: 123:23:21

The three separate numbers could range from 1 to 99999, it's essentially a key to represent a set of data.

I need to extract each of the separate numbers

  • The first before the colon "123"
  • The second between the first colon "32" and last colon
  • The third after the last colon "21"

I've found a few answers (below), but don't provide enough info for a complete amateur to do what I need too.

These are completely wrong but I've tried variations of ^\w+:$, ^:\w+:$, ^:\w+$.

Can anyone give me a heads up as to how to implement this in Java? Could be regex or substring.

Community
  • 1
  • 1
user1974297
  • 63
  • 12

6 Answers6

2

In java, u can use split method of String or can use Scanner.useDelimiter(pattern)

Ex-

String str = "123:23:21";
String[] nums = str.split(":");

num[0] - 123, num[1] = 23, num[2] = 21 //output
Arjit
  • 3,290
  • 1
  • 17
  • 18
1

Get rid of the ^ and $, as these, respectively, indicate the start and end of the string.

Try just \w+ (the : can be omitted since \w doesn't include :, and wouldn't work too well at the start and end of the string, unless you make it optional).

Then you'll use Matcher.find() to find each occurrence.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
0

This will help you to match the number from 1 - 99999 separated by colon.

String input = "text 123:23:99999 number";
Pattern pattern = Pattern.compile("(?:\\D|^)([1-9][0-9]{0,4}):([1-9][0-9]{0,4}):([1-9][0-9]{0,4})(?:\\D|$)");
Matcher m = pattern.matcher(input);
if (m.find()) {
    System.out.println(m.group(1));
    System.out.println(m.group(2));
    System.out.println(m.group(3));
}
Sabuj Hassan
  • 38,281
  • 14
  • 75
  • 85
0

You can split() -

String string = "123:23:21";
String[] parts = string.split(":");
for(String p:parts){
    System.out.println(p);
}
/* OUTPUT */
123
23
21
Kamehameha
  • 5,423
  • 1
  • 23
  • 28
0

For the string 123:32:21 You can use [^:]+: to get 123: and :[^:]+: to get :32: and :[^:]+ to get :21 and the remove the : from the string

A nice explanation for regex is give in http://www.beedub.com/book/2nd/regexp.doc.html

anirudh
  • 4,116
  • 2
  • 20
  • 35
0

First of all \w matches word chatacters. For only numbers you need \d. You can extract all three numbers with one regexp using matching groups.

(\d+)\:(\d+)\:(\d+)

Dont forget to write double backslashes if you init your Pattern. From a Matcher which is created by your Pattern you then get the group data. Groups are the ( ) areas from your regexp.

You could improve this by ^ and $ like you already did to force line boundaries.

wumpz
  • 8,257
  • 3
  • 30
  • 25