Reputation: 457
I have a string that is dynamially generated.
I need to split the string based on the Relational Operator.
For this I can use the split function.
Now I would also like to know that out of the regex mentioned above, based on which Relational Operator was the string actually splitted.
An example, On input
String sb = "FEES > 200";
applying
List<String> ls = sb.split(">|>=|<|<=|<>|=");
System.out.println("Splitted Strings: "+s);
will give me the result,
Splitted strings: [FEES , 200 ]
But expecting result:
Splitted strings: [FEES , 200 ]
Splitted Relational Operator: >
Upvotes: 10
Views: 747
Reputation: 10789
I suggest to use regex, which is more flexible in your case.
String sb = "FEES > 200";
Pattern pat = Pattern.compile("(.*?)(>=|<=|<>|=|>|<)(.*)");
Matcher mat = pat.matcher(sb);
if (mat.find()) {
System.out.println("Groups: " + mat.group(1) + ", " + mat.group(3));
System.out.println("Operator: " + mat.group(2));
}
Upvotes: 3
Reputation: 163467
You could use 3 capturing groups with an alternation for the second group:
(.*?)(>=|<=|<>|>|<)(.*)
Explanation
(.*?)
Match any character zero or more times non greedy(>=|<=|<>|>|<)
Match either >=
or <=
or <>
or >
or <
(.*)
Match any character zero or more timesFor example:
String regex = "(.*?)(>=|<=|<>|>|<)(.*)";
String string = "FEES >= 200";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
if(matcher.find()) {
System.out.println("Splitted Relational Operator: " + matcher.group(2));
System.out.println("Group 1: " + matcher.group(1) + " group 3: " + matcher.group(3));
}
Upvotes: 15
Reputation: 2147
Use Pattern
to do this.
String sb = "FEES > 200";
Pattern pattern = Pattern.compile("(.*)(>|>=|<|<=|<>|=)(.*)");
Matcher matcher = pattern.matcher(sb);
if (matcher.find()) {
System.out.println("Grouped params: " + matcher.group(1) + "," + matcher.group(3));
System.out.println("Split operator: " + matcher.group(2));
}
Note that :
matcher.group(0)
--> All stringmatcher.group(1)
--> first part of matchingmatcher.group(2)
--> split operatormatcher.group(3)
--> second part of matchingUpvotes: 1
Reputation:
You can use replaceAll() if you want exclude number from your string:
replaceAll("\d", ""); - this replace all number on white space
To delete unnecessary words you need to give more information. Because there are different ways of doing things.
Upvotes: 0
Reputation: 1073
You can use Pattern matcher
to match the delimeters. Example shown below -
public static int indexOf(Pattern pattern, String s) {
Matcher matcher = pattern.matcher(s);
return matcher.find() ? matcher.start() : -1;
}
public static void main(String[] args) {
String sb = "FEES > 200";
String[] s = sb.split(">|>=|<|<=|<>|=");
System.out.println("Splitted Strings: "+ s);
int index = indexOf(Pattern.compile(">|>=|<|<=|<>|="), sb);
System.out.println("del "+ sb.charAt(index));
}
Upvotes: 0