Compare 2 strings in Java upto a delimiter - java

String 1:
func1(test1)
String 2:
func1(test2)
I want to compare these 2 strings upto the first open braces '('.
So for the given example it should return true since the string upto '(' in both the strings is 'func1'.
Is there any way to do that without splitting?

String#substring() method will help on this case this combined with String#indexOf() method
String x1 = "func1(test1)";
String x2 = "func1(test1)";
String methName1 = x1.substring(0, x1.indexOf("("));
String methName2 = x2.substring(0, x2.indexOf("("));
System.out.println(methName1);
System.out.println(methName2);
System.out.println(methName1.equals(methName2));

You can use String.matches() method to test if the second string matches the splitted one from the first string:
String s1 = "func1(test1)";
String s2 = "func1(test2)";
String methName = s1.substring(0, s1.indexOf("("));
System.out.println(s2.matches(methName+ "(.*)"));
This is a working Demo.

Alternatively you can compare the strings directly by replacing everything after '(' by empty string.
String str1 = "func1(test1)";
String str2 = "func1(test2)";
System.out.println(str1.replaceAll("\\(.*", "").equals(str2.replaceAll("\\(.*", "")));

You can use regex to find every thing between any delimiters, in your case () and compare the results, for example :
String START_DEL = "\\("; //the start delimiter
String END_DEL = "\\)"; //the end delimiter
String str1 = "func1(test1)";
String str2 = "func1(test2)";
Pattern p = Pattern.compile(START_DEL + "(.*?)" + END_DEL);//This mean "\\((.*?)\\)"
Matcher m1 = p.matcher(str1);
Matcher m2 = p.matcher(str2);
if (m1.find() && m2.find()) {
System.out.println(m1.group(1).equals(m2.group(1)));
}

Related

How to split Strings in java

I have two types of Strings. One is "abcdEfgh" and "abcd efgh". That means first String is having upper case letter in between and second string is having white space. So now how do I check these two pattern string in java and make two strings.
String givenString;
if (givenString.equals("abcdEfgh")) {
String str1 = abcd;
String str2 = Efgh;
} else (givenString.equals("abcd efgh") {
String str1 = abcd;
String str2 = efgh;
}
Please provide the solution
Thanks
You can split using regex \\s|(?=[A-Z])
\\s is to deal with case of whitespace.
(?=[A-Z])is positive lookahead. It finds capital letter but keeps the delimiter while splitting.
.
String givenString;
String split[] = givenString.split("\\s|(?=[A-Z])");
String str1 = split[0];
String str2 = split[1];
for both cases
Test case 1
//case 1
givenString = "abcdEfgh";
str1 = abcd
str2 = Efgh
Test case 2
//case 2
givenString = "abcd efgh";
str1 = abcd
str2 = efgh
You need to combine the two conditions using the OR operator |. You've already figured out split by space is simply " ". The uppercase example is answered by Java: Split string when an uppercase letter is found
Example
String one = "abcdEfgh";
String two = "abcd efgh";
System.out.println(Arrays.toString(one.split(" |(?=\\p{Upper})")));
System.out.println(Arrays.toString(two.split(" |(?=\\p{Upper})")));
Output
[abcd, Efgh]
[abcd, efgh]
Keep it simple, search for space in givenString instead of case sensitive matchs
if(givenString.indexOf(" ") != -1){
System.out.println( "The string has spaces");
}else{
System.out.println( "The string has NO spaces");
}

extra space after parsing a string with regular expression

I have the following simple code:
String d = "_|,|\\.";
String s1 = "b,_a_.";
Pattern p = Pattern.compile(d);
String[] ss = p.split(s1);
for (String str : ss){
System.out.println(str.trim());
}
The output gives
b
a
Where does the extra space come from between b and a?
You do not have an extra space, you get an empty element in the resulting array because your regex matches only 1 character, and when there are several characters from the set on end, the string is split at each of those characters.
Thus, you should match as many of those characters in your character class as possible with + (1 or more) quantifier by placing the whole expression into a non-capturing group ((?:_|,|\\.)+), or - better - using a character class [_,.]+:
String d = "(?:_|,|\\.)+"; // Or better: String d = "[_,.]+";
String s1 = "b,_a_.";
Pattern p = Pattern.compile(d);
String[] ss = p.split(s1);
for (String str : ss){
System.out.println(str.trim());
}
See IDEONE demo
While i get puzzled my self, maybe what you want is to change your regex to
String d = "[_,\\.]+";

String replace according to position?

I have this String 11101011.I want to replace last three char '011' with 101.is there any function of String in java to do so?
Use string.replaceAll function.
string.replaceAll(".{3}$", "101");
.{3} matches exactly three characters and $ asserts that the match must be followed by an end of the line.
Example:
String name = "11101011";
String result = name.replaceAll(".{3}$", "101");
System.out.println(result);
Output:
11101101
Using String replace and regular expressions for this task seems like breaking butterflies on a wheel - just cut the last three characters off and append the new suffix (ultimately verbose solution):
final String oldString = "11101011";
final String oldSuffix = oldString.substring(5);
final String reducedOldString = oldString.substring(0, oldString.length() - oldSuffix.length());
final String newSuffix = "101";
final String newString = reducedOldString.concat(newSuffix);
System.out.println("newString = " + newString);
Use replace method of String class
String s="11101011";
System.out.println(s.replace("011","101"));
O/P:
11101101

Split Java String

Title seems to be simple. But I don't get a good Idea. This is the situation
I have String like this in my Java program
String scz="3282E81WHT-22/24";
I want to split the above string into 3 Strings, such that
first string value should be 3282e81,
Next string should be WHT(ie, the String part of above string and this part is Always of 3 Characters ),
Next String value should be 22/24 (Which will always occur after -)
In short
String first= /* do some expression on scz And value should be "3282e81" */;
String second= /* do some expression on scz And value should be "WHT" */;
String third= /* do some expression on scz And value should be "22/24" */;
Input can also be like
scz="324P25BLK-12";
So 324P25 will be first String, BLK will be second (of 3 Characters). 12 will be third ( After - symbol )
How to solve this?
You can use a regex like this (\d+[A-Z]\d+)([A-Z]+)-([/\d]+) and using Matcher.group(int) method you can get your string splitted into three groups.
Code snippet
String str = "3282E81WHT-22/24";
//str = "324P25BLK-12";
Pattern pattern = Pattern.compile("(\\d+[A-Z]\\d+)([A-Z]+)-([/\\d]+)");
Matcher match = pattern.matcher(str);
System.out.println(match.matches());
System.out.println(match.group(1));
System.out.println(match.group(2));
System.out.println(match.group(3));
Output
true
3282E81
WHT
22/24
Use this to split the entire string in to two
String[] parts = issueField.split("-");
String first = parts[0];
String second= parts[1];
Use this to split the first string into two
if (first!=null && first.length()>=3){
String lastThree=first.substring(first.length()-3);
}
if your String's Second part (WHT) etc will always be of 3 Characters then following code will surely help you
String scz = "3282E81WHT-22/24";
String Third[] = scz.split("-");
String rev = new StringBuilder(Third[0]).reverse().toString();
String Second=rev.substring(0,3);
String First=rev.substring(3,rev.length());
// here Reverse your String Back to Original
First=new StringBuilder(First).reverse().toString();
Second=new StringBuilder(Second).reverse().toString();
System.out.println(First + " " + Second + " " + Third[1]);
You can use subString() method to get this goals.
subString has numbers of overloads.
for first string
String first=scz.subString(0,6);
String second=scz.subString(7,9);
You can use following regex to take out the above type string:
\d+[A-Z]\d{2}|[A-Z]{3}|(?<=-)[\d/]+
In Java, you can use above regex in following way:
Pattern pattern = Pattern.compile("\\d+[A-Z]\\d{2}|[A-Z]{3}|(?<=-)[\\d/]+");
Matcher matcher = pattern.matcher("3282E81WHT-22/24");
while (matcher.find()) {
System.out.println(matcher.group());
}
Output:
3282E81
WHT
22/24
You could us a char array instead of a string so you can access specific characters withing the array.
Example
char scz[] = "3282E81WHT-22/24";
and access the separate characters just by specifying the place in which the array you want to use.
You can try this
String scz="3282E81WHT-22/24";
String[] arr=scz.split("-");
System.out.println("first: "+arr[0].substring(0,7));
System.out.println("second: "+arr[0].substring(7,10));
System.out.println("third: "+arr[1])
Check out my solution -
class Main {
public static void main(String[] args) {
String first = "";
String second = "";
String third = "";
String scz="3282E81WHT-22/24";
String[] portions = scz.split("-");
if (portions.length > 1) {
third = portions[1];
}
String[] anotherPortions = portions[0].split("[a-zA-Z]+$");
if (anotherPortions.length > 0) {
first = anotherPortions[0];
}
second = portions[0].substring(first.length());
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
Live Demo.
String scz="3282E81WHT-22/24";
String[] array = scz.split("-");
String str1 = (String) array[0].subSequence(0, 7);
String str2 = array[0].substring(7);
Then the split will be in this order :)
str1
str2
array[1]
if the length of string is fixed for scz, first,second and third the you can use
String first=scz.subString(0,6);
String second=scz.subString(7,9);
String third=scz.subString(10,scz.length());

Java split regular expression

If I have a string, e.g.
setting=value
How can I remove the '=' and turn that into two separate strings containing 'setting' and 'value' respectively?
Thanks very much!
Two options spring to mind.
The first split()s the String on =:
String[] pieces = s.split("=", 2);
String name = pieces[0];
String value = pieces.length > 1 ? pieces[1] : null;
The second uses regexes directly to parse the String:
Pattern p = Pattern.compile("(.*?)=(.*)");
Matcher m = p.matcher(s);
if (m.matches()) {
String name = m.group(1);
String value = m.group(2);
}
The second gives you more power. For example you can automatically lose white space if you change the pattern to:
Pattern p = Pattern.compile("\\s*(.*?)\\s*=\\s*(.*)\\s*");
You don't need a regular expression for this, just do:
String str = "setting=value";
String[] split = str.split("=");
// str[0] == "setting", str[1] == "value"
You might want to set a limit if value can have an = in it too; see the javadoc

Categories