Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Combine two Regular expressions

 
Vikram Ramaswamy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
String s= "[12/22/09 22:23:57:357 MST] Some junk text that I am not interested in or not required. There is/are 10 more junk text"

From the above string, I would like to extract the time (stuff between []) and the number (10 in this case) that would look like this;
[12/22/09 22:23:57:357 MST] 10

I tried using the RE \[.*\]|\s\d\d?\s, but the problem is I get [12/22/09 22:23:57:357 MST] when I use \[.*\] and 10 when I use \s\d\d?\s, but when I combine them with a "|", I get only the date. I tried searching forums in vain, but am stuck. Any help is appreciated.
 
Henry Wong
author
Marshal
Pie
Posts: 21498
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, how did you combine them? Just "with a "|"", doesn't tell us anything.

Henry
 
Vikram Ramaswamy
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I apologise if it wasnt clear enough...The Regular Expression I tried was \[.*\]|\s\d\d?\s hoping to extract [12/22/09 22:23:57:357 MST] 10 from string "[12/22/09 22:23:57:357 MST] Some junk text that I am not interested in or not required. There is/are 10 more junk text", but it isn't working as expected. It extracts only [12/22/09 22:23:57:357 MST] (including the square brackets), but not the number (10).
 
Henry Wong
author
Marshal
Pie
Posts: 21498
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh I see. You want the regex engine to extract two different parts from the string, and merge it as one result for you.... Nope. Can't be done. Regex doesn't work that way.

The best you can do is have a regex with groups -- one for each component. And then form the result from the match group (ie. create the merged string yourself using a string concat).

Henry
 
Mazer Lao Tzu
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The simple explanation is to create a regular expression that will match with the entire line of text and put parentheses around what you want. This is called grouping. Read about java.util.regex.Matcher and look at retrieving groups.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic