Connect with Expertise | Find Experts, Get Answers, Share Insights

helping with regex in java.

 
Join Date: Jan 2009
Posts: 78
#1: Mar 3 '10
If I have a line that contains this: ProdBC02TradeServer24
and I want to break it up into BC02 and 24, how would I go about doing that.

Right now,
I am doing this: Prod(BC\\d+)\\S+(\\d+)
But that only breaks it up into:
BC02 and 4. I need 24, not just the 4.
Can someone show me what I am doing wrong

Thanks
Nirav

jkmyoung's Avatar
E
M
C
 
Join Date: Mar 2006
Posts: 1,938
#2: Mar 4 '10

re: helping with regex in java.


The problem is that the regex picks the shortest match, eg the match with only 1 digit. I suggest adding the next character, whether that be space, end of line, eof, or other.

What class are you using to execute the regexp?
 
Join Date: Jan 2009
Posts: 78
#3: Mar 4 '10

re: helping with regex in java.


I am importing these two lines:
Expand|Select|Wrap|Line Numbers
  1. import java.util.regex.Matcher;
  2. import java.util.regex.Pattern;
  3.  
I am defining the regex expressing in a variable here:
Expand|Select|Wrap|Line Numbers
  1. public static String TSAssingmentFilter = "Prod(BC\\d+)\\S+(\\d+)\\s+(\\w+)\\s+\\S+\\s+(\\d+)\\s+(\\S*)\\s+(\\d+)";
  2.  
I am using this function to use the regex expression on the specific line:
Expand|Select|Wrap|Line Numbers
  1. if(OutlierUtilities.getInstance().match(line,TSAssingmentFilter))
  2.  
I am using this function to grep out what i am looking for:
Expand|Select|Wrap|Line Numbers
  1. public boolean match(String line,String regExp)
  2.      {
  3.               pattern = Pattern.compile(regExp);
  4.               matcher = pattern.matcher(line);
  5.               return matcher.find();
  6.      }
  7.  
jkmyoung's Avatar
E
M
C
 
Join Date: Mar 2006
Posts: 1,938
#4: Mar 4 '10

re: helping with regex in java.


Insert a non digit character afterwards: \D or [^\d], and change the \\s+ to a \\s?
 
Join Date: Jan 2009
Posts: 78
#5: Mar 4 '10

re: helping with regex in java.


so instead of this: Prod(BC\\d+)\\S+(\\d+)

are you saying I should try this: Prod(BC\\d+)\\S\\D(\\d+)
jkmyoung's Avatar
E
M
C
 
Join Date: Mar 2006
Posts: 1,938
#6: Mar 4 '10

re: helping with regex in java.


"Prod(BC\\d+)\\S+(\\d+)\\s+ ..."to
"Prod(BC\\d+)\\S+(\\d+)[^\\d]\\s?..."
 
Join Date: Jan 2009
Posts: 78
#7: Mar 4 '10

re: helping with regex in java.


Im sorry...im having trouble in this part:
Prod(BC\\d+)\\S+(\\d+)
But that only breaks it up into:
BC02 and 4. I need 24, not just the 4.

So i changed it to this and it worked:
Expand|Select|Wrap|Line Numbers
  1. public static String TSAssingmentFilter = "Prod(BC\\d+)\\S+\\D(\\d+)\\s+(\\w+)\\s+\\S+\\s+(\\d+)\\s+(\\S*)\\s+(\\d+)";
  2.  
THANKS A LOT FOR YOUR HELP!!!
Reply