Reputation: 4768
I have a string that is always built likeMfr Part#: MBRB1045G Technologie ...
or Mfr Part#: MBRB1545CTT4G Mounting
, so there is always Mfr Part#:
then the partnumber
I want to extract and then this is followed by either Technologie
or Mounting
entailed by other characters.
How would you extract that partnumber MBRB1045G
from this?
Upvotes: 0
Views: 79
Reputation: 10218
This should do the trick:
final Pattern pattern = Pattern
.compile("Mfr Part#: ([^ ]+) (Technologie|Mounting).*");
final Matcher matcher = pattern
.matcher("Mfr Part#: MBRB1045G Mounting");
matcher.matches();
System.out.println(matcher.group(1));
However, if it's not important to you to check that the string has that specific pattern, you might also use the simpler expression: Mfr Part#: ([^ ]+) .*
Also note that you may store the pattern object and reuse it for subsequent usages. This will give you a better performance.
Upvotes: 3
Reputation: 47608
I see two ways to do that (and there are likely others): regexp and groups, or indexOf and substring
1) Regexp and groups
String input = "Mfr Part#: MBRB1045G Technologie";
Pattern p = Patter.compile("Mfr Part#: ([A-Z0-9]+) (Technologie|Mounting)");
Matcher m = p.matcher(input);
while(m.find()) {
System.err.println("Part number: "+m.group(1)+ "Second part is "+m.group(2);
}
2) indexOf and substring
String prefix = "Mfr Part#: ";
String input = "Mfr Part#: MBRB1045G Technologie";
for (int i= 0;i<input.length();i++) {
int index1 = input.indexOf(prefix);
int index2 = index1+prefix.length();
int index3 = input.indexOf(" ", );
int index4 = input.indexOf(" ", index3+1);
System.err.println("Part number: "+input.substring(index2, index3)
+ "Second part is "+input.substring(index3, index4);
index = index4;
}
Caveats: I have not run it so you may have to fix typos.
Upvotes: 0
Reputation: 11805
Probably a regular expression with grouping would be best. (google for perlre)
String input = "Mfr Part#: MBRB1045G Technologie";
String regexpression = "Mfr Part#: (\\w+) (\\w+)";
Pattern p = Pattern.compile(regexpression);
Matcher m = p.matcher(input);
if (m.matches()) {
String part = m.group(1);
String desc = m.group(2);
System.out.println(part);
System.out.println(desc);
}
Upvotes: 0
Reputation: 3608
I would probably use java.util.Scanner
. It might not be the optimal way to do so but in my oppinion the most comfortable.
It would work this way:
import java.util.Scaner;
String s = "Mfr Part#: MBRB1045G Technologie RZ137GA";
Scanner scn = new Scanner(s);
scn.next();
scn.next();
String partnumber = scn.next();
scn.next();
String technologie = scn.next();
scn.close();
The variable partnumber
would contain MBRB1045G
and technologie
contains RZ137GA
.
Upvotes: 0