Split the string with different length - java

I have a String String s = " ABCD 1122-12-12", i.e <space or single digit number>+<any string>+<space>+<date in YYYY-mm-dd> format.
What could be the regex for String.split method or any other utility methods to split the above string into three parts
[0] = <space or single digit number> = " "
[1] = <string> = "ABCD"
[2] = <date in YYYY-mm-dd> = "1122-12-12"

The regex ( |\d)(.+) (\d{4}-\d{2}-\d{2}) should do the job.
String input = " ABCD 1122-12-12";
Pattern pattern = Pattern.compile("( |\\d)(.+) (\\d{4}-\\d{2}-\\d{2})");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
String spaceOrDigit = matcher.group(1);
String string = matcher.group(2);
String date = matcher.group(3);
System.out.println("spaceOrDigit = '" + spaceOrDigit + "'");
System.out.println("string = '" + string + "'");
System.out.println("date = '" + date + "'");
}
Output:
spaceOrDigit = ' '
string = 'ABCD'
date = '1122-12-12'

Related

split String If get any capital letters

My String:
BByTTheWay .I want to split the string as B By T The Way BByTheWay .That means I want to split string if I get any capital letters and last put the main string as it is. As far I tried in java:
public String breakWord(String fileAsString) throws FileNotFoundException, IOException {
String allWord = "";
String allmethod = "";
String[] splitString = fileAsString.split(" ");
for (int i = 0; i < splitString.length; i++) {
String k = splitString[i].replaceAll("([A-Z])(?![A-Z])", " $1").trim();
allWord = k.concat(" " + splitString[i]);
allWord = Arrays.stream(allWord.split("\\s+")).distinct().collect(Collectors.joining(" "));
allmethod = allmethod + " " + allWord;
// System.out.print(allmethod);
}
return allmethod;
}
It givs me the output: B ByT The Way BByTTheWay . I think stackoverflow community help me to solve this.
You may use this code:
Code 1
String s = "BByTTheWay";
Pattern p = Pattern.compile("\\p{Lu}\\p{Ll}*");
String out = p.matcher(s)
.results()
.map(MatchResult::group)
.collect(Collectors.joining(" "))
+ " " + s;
//=> "B By T The Way BByTTheWay"
RegEx \\p{Lu}\\p{Ll}* matches any unicode upper case letter followed by 0 or more lowercase letters.
CODE DEMO
Or use String.split using same regex and join it back later:
Code 2
String out = Arrays.stream(s.split("(?=\\p{Lu})"))
.collect(Collectors.joining(" ")) + " " + s;
//=> "B By T The Way BByTTheWay"
Use
String s = "BByTTheWay";
Pattern p = Pattern.compile("[A-Z][a-z]*");
Matcher m = p.matcher(s);
String r = "";
while (m.find()) {
r = r + m.group(0) + " ";
}
System.out.println(r + s);
See Java proof.
Results: B By T The Way BByTTheWay
EXPLANATION
--------------------------------------------------------------------------------
[A-Z] any character of: 'A' to 'Z'
--------------------------------------------------------------------------------
[a-z]* any character of: 'a' to 'z' (0 or more
times (matching the most amount possible))
As per requirements, you can write in this way checking if a character is an alphabet or not:
char[] chars = fileAsString.toCharArray();
StringBuilder fragment = new StringBuilder();
for (char ch : chars) {
if (Character.isLetter(ch) && Character.isUpperCase(ch)) { // it works as internationalized check
fragment.append(" ");
}
fragment.append(ch);
}
String.join(" ", fragment).concat(" " + fileAsString).trim(); // B By T The Way BByTTheWay

How to pass variable in regex-Java to make a script dynamic?

I have this function written in Java-Selenium and wondering how I can pass a variable(key) in place of evar90? Your support will be appreciated a lot.
public void verifyXyz(String key,String expectedResult) {
selenium.waitForPageLoad();
String resultString = selenium.executeJSCall("localStorage.getItem('s.tl-data')");
String matchedString = "";
String variable = "key";
Pattern pattern = Pattern.compile("(eVar90=[^:]*)");
Matcher matcher = pattern.matcher(resultString);
if (matcher.find()) {
matchedString = matcher.group();
}
Assert.assertTrue("Product variable does not match expected value \n"
+ "Expected: " + expectedResult + " \n"
+ "Actual: " + matchedString
, matchedString.equals(expectedResult));
}
Thank you in Advance!

Java split method

I am trying to split an inputted number such as (123) 456-7890.
String [] split = s.split(delimiters);
I have been searching the web for ways of delimiting the area code inside the set of the parentheses but I haven't found anything that works for my case. I do not know if the array is messing up with it printing either. The array is not required but I did not know what else to do since it is required to use the split method.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HelloWorld{
public static void main(String[] args){
String phoneNumber = "(123)-456-7890";
String pattern = "\\((\\d+)\\)-(\\d+)-(\\d+)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(phoneNumber);
if (m.find())
System.out.println(m.group(1) + " " + m.group(2) + " " + m.group(3));
}
}
You can try it here.
If I understand your question, you could use a Pattern like (XXX) XXX-XXXX where X is a digit. You can also use {n} to require n occurences. You group with (). Something like,
String str = "(123) 456-7890";
Pattern p = Pattern.compile("\\((\\d{3})\\) (\\d{3})-(\\d{4})");
Matcher m = p.matcher(str);
if (m.matches()) {
String areaCode = m.group(1);
String first3digits = m.group(2);
String last4digits = m.group(3);
System.out.printf("(%s) %s-%s%n", areaCode, first3digits,
last4digits);
}
Gives your requested output of
(123) 456-7890
or, if you must use split you might first remove the ( and ) with a call to replaceAll and something like
String str = "(123) 456-7890";
String[] arr = str.replaceAll("[()]", "").split("[ -]");
System.out.printf("(%s) %s-%s%n", arr[0], arr[1], arr[2]);
which also gives your requested output of
(123) 456-7890
this works:
String s= "(123) 456-7890";
String[] parts = s.split("[()\\- ]");
System.out.println("(" + parts[1] + ") " + parts[3] + "-" + parts[4]);
If you must use the split method:
String s= "(123) 456-7890"
String[] split = s.split("[()-]");
System.out.println("(" + split[1] + ")" + split[2] + "-" + split[3]);

How to perform string manipulation using replace, substring, split, etc

I have a string data like this
string1 = ["car","house","boat"]["one","two","three","four"]["tiger","cat"]
I want the output to be like this :
first : car,house,boat
second : one,two,three,four
third : tiger,cat
How should I perform manipulation on that string?
This is my current attempt:
result6 = string1.substring(1);
String[] parts = result6.split("\\[");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
result3 = part1.replaceAll("[^a-zA-Z0-9,]", "");
result4 = part2.replaceAll("[^a-zA-Z0-9,]", "");
result5 = part3.replaceAll("[^a-zA-Z0-9,]", "");
result1 = "first : " + part1 + "\n" + "second : " + part2 + "\n" + "third : \n" + part3;
But that gets me erroneous output.
You have added part1, part2, part3 instead of result3, 4, 5 in the result1 assignment part. And also i suggest you to split according to ][, i you do the split according to [ only, you would get an empty string in parts[0].
String string1 = "[\"car\",\"house\",\"boat\"][\"one\",\"two\",\"three\",\"four\"][\"tiger\",\"cat\"]";
String parts[] = string1.split("\\]\\[");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];
String result3 = part1.replaceAll("[^a-zA-Z0-9,]", "");
String result4 = part2.replaceAll("[^a-zA-Z0-9,]", "");
String result5 = part3.replaceAll("[^a-zA-Z0-9,]", "");
String result1 = "first : " + result3 + "\n" + "second : " + result4 + "\n" + "third : " + result5;
System.out.println(result1);
Output:
first : car,house,boat
second : one,two,three,four
third : tiger,cat

java regex to match variable

I have the name of a java variable in a string. I want to replace it with the letter x. How can I do this java, and make sure that other words in the string are not replaced ?
For example, say my variable is res, and my string is "res = res + pres + resd + _res. I want the string to become x = x + pres + resd + _res.
You can use a word boundary to only capture whole words:
String s = "res = res + pres + resd + _res";
String var = "res";
System.out.println(s.replaceAll("\\b" + var + "\\b", "x"));
outputs x = x + pres + resd + _res
You can use the \b metacharacter to match a word boundary. (Bear in mind you'll need to use doule backslashes to escape this in Java.)
So you can do something like the following:
final String searchVar = "res";
final String replacement = "x";
final String in = "res = res + pres + resd + _res";
final String result = in.replaceAll("\\b" + searchVar + "\\b", replacement);
System.out.println(result);
// prints "x = x + pres + resd + _res"

Categories

Resources