Reputation: 1437
I have input like "Varchar(10)
, Number(10)
, datetime(8)
, varchar(17)
, char(3)
at a time one.
I need to extract only text from it. How can I do it in Java?
Lets say I have input Varchar(50)
and expecting output Varchar
.
I tried this, but it did not work:
String line = "varchar(0)";
String pattern = "\\D{.*}";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
} else {
System.out.println("NO MATCH");
}
Upvotes: 2
Views: 480
Reputation: 31296
I think a regular expression is overkill if you're only dealing with single appearences.
For example:
s = val.substring(1, val.indexOf ('('))
would do the job. Although this would always expect to see '(' as part of the input string.
Upvotes: 0
Reputation: 1840
Your group regular expression is in general
\w+\(\d+\)
and to capture the first part, you can make it into a group
(\w+)\(\d+\)
Try this function:
private final Pattern TYPE_REGEX = Pattern.compile("(\\w+)\\(\\d+\\)");
public String extractType(String item) {
Matcher matcher = TYPE_REGEX.matcher(item.trim());
if(!matcher.matches())
return null;
return matcher.group(1);
}
Freebie:
You might also use a typesafe enum, for your return type, as I think you're dealing with a fixed set of database types
private enum Type { VARCHAR, NUMBER, DATETIME, CHAR, ADD_ALL_OTHERS_THAT_APPLY }
private final Pattern TYPE_REGEX = Pattern.compile("(\\w+)\\(\\d+\\)");
public Type extractType(String item) {
Matcher matcher = TYPE_REGEX.matcher(item.trim());
if(!matcher.matches())
return null;
return Type.valueOf(matcher.group(1).toUpperCase());
}
Upvotes: 2
Reputation: 25950
You can split your input string with this regex "\\(\\d+\\),*"
:
Sample code:
String str = "Varchar(10), Number(10), datetime(8), varchar(17), char(3)";
String[] parts = str.split("\\(\\d+\\),*");
for (String part : parts)
System.out.println(part.trim());
Output (Note that trim()
is invoked before printing an element.):
Varchar
Number
datetime
varchar
char
Upvotes: 0