Regex for a string pattern split [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Have a scenario to strip the below pattern strings -
abc|hjdj|kleygag|0|0|0|0|
ghys|jkugb|0|0|0
yuubf|kluygb|tyrffv|nutgv|0|0|0|0|0|
Looking for help to get a regex in java to separate these values excluding everything from the first occurence of pipe before 0, the output should look like-
abc|hjdj|kleygag
ghyd|jkugb
yuubf|kluygb|tyrffv|nutgv
Just need regex, which has been answered and been very helpful, would just be very helpful to know just the regex and not the complete code for the reverse pattern as requested in the followup question

Is regex necessary for this? substring() gets you want you want easily.
Update
I saw a comment where you're also wanting a case where the data looks like, "0|0|0|0|abdc|ghyft|rtyu". I've modified my answer to account for that case and a case where the data could be, "0|0|0|0|abdc|ghyft|rtyu|0|0|0|"
Either way:
public static void main(String[] args) throws Exception {
List<String> strings = new ArrayList(){
{
add("abc|hjdj|kleygag|0|0|0|0|");
add("ghys|jkugb|0|0|0");
add("yuubf|kluygb|tyrffv|nutgv|0|0|0|0|0|");
add("0|0|0|0|abdc|ghyft|rtyu");
add("0|0|0|0|abdc|ghyft|rtyu|0|0|0|0|0|");
}
};
// Non Regex
System.out.println("Non Regex");
for (String string : strings) {
int startIndex = -1;
int endIndex = -1;
// Find first non zero character
for (int i = 0; i < string.length(); i++) {
if ('a' <= string.charAt(i) && string.charAt(i) <= 'z') {
startIndex = i;
break;
}
}
// Find first pipe zero |0 after startIndex
endIndex = string.indexOf("|0", startIndex);
// Determine which substring() to use based on the endIndex results
System.out.println(endIndex > -1 ? string.substring(startIndex, endIndex) : string.substring(startIndex));
}
System.out.println("");
// Regex
System.out.println("Regex");
for (String string : strings) {
System.out.println(string.replaceAll("\\|0|0\\||\\|$", ""));
}
}
Results:
Non Regex
abc|hjdj|kleygag
ghys|jkugb
yuubf|kluygb|tyrffv|nutgv
abdc|ghyft|rtyu
abdc|ghyft|rtyu
Regex
abc|hjdj|kleygag
ghys|jkugb
yuubf|kluygb|tyrffv|nutgv
abdc|ghyft|rtyu
abdc|ghyft|rtyu

You can use a regex like this:
\|0|0\||\|$
Java code:
String regex = "\\|0|0\\|\\|$";
System.out.println("abc|hjdj|kleygag|0|0|0|0|".replaceAll(regex, ""));
System.out.println("ghys|jkugb|0|0|0".replaceAll(regex, ""));
System.out.println("yuubf|kluygb|tyrffv|nutgv|0|0|0|0|0|".replaceAll(regex, ""));

Related

Taking the first Char of a String until the String is empty "" [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am currently working on a task and I have a question about the Substring method.
For the task I need to get the first Char of a String and delete the first Char after I used it.
The Strings are names and at the end I only want to have "" an empty String left.
My approach:
String name = "Paul";
char chr = name.charAt(0);
String newName = name.substring(1);
My questions: When I am at the last char "l" and use my substring do I get "" or an error?
My questions: When I am at the last char "l" and use my substring do I
get "" or an error?
You will get a blank string. It is also mentioned in the following lines of documentation:
Throws:
IndexOutOfBoundsException - if beginIndex is negative or larger than the length of this String object.
When you have only l left in the string, its length will be 1 which is perfectly acceptable as the beginIndex. You can also verify it as follows:
public class Main {
public static void main(String[] args) {
System.out.println("l".substring(1));
}
}
To make sure that is error free, do the following.
String name = "Paul";
int nameLength = name.length();
for (int i = 0; i < nameLength; i++){
char chr = name.charAt(0);
if (i != nameLength - 1){
String newName = name.substring(1);
name = newName;
} else {
name = "";
}
}

Hide characters after certain index with symbols [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I understand that I did a lot of hard coding that can be avoided so if anything can share their thought please go ahead:
private String hideEmailCharacters(String privateEmail){
String emailName = privateEmail.substring(0,privateEmail.indexOf("#"));
StringBuilder stringBuffer = new StringBuilder(emailName);
stringBuffer.replace(emailName.length() / 2,emailName.length(), StringUtils.repeat("*", emailName.length() / 2));
String emailProvider = privateEmail.substring(privateEmail.indexOf("#"));
return stringBuffer + emailProvider;
}
The goal is to cover for example half of the email name or cover everything after the second character with stars ** so the result from abcdv#example.com would be ab***#example.com
String processing is cool but here's a solution with Regular Expression.
(?<=.{2}).(?=[^#]*?#)
Intuition:
Ignore first 2 characters from the characters before #
Ignore # as well.
Replace each character between with *
public class TestCode {
private static String hideEmailCharacters(String privateEmail) {
return privateEmail.replaceAll("(?<=.{2}).(?=[^#]*?#)", "*");
}
public static void main(String[] args) {
System.out.println(hideEmailCharacters("abcdv#example.com"));
System.out.println(hideEmailCharacters("ra0o29ajzsdc242#example.com"));
System.out.println(hideEmailCharacters("x2helloyouthere#example.com"));
System.out.println(hideEmailCharacters("a#foo.com"));
}
}
Output:
ab***#example.com
ra*************#example.com
x2*************#example.com
a#foo.com
This piece of code will do the trick:
StringBuffer email = new StringBuffer(privateEmail)
int startIndex = email.indexOf("#")/2;
int endIndex = email.indexOf("#");
int numOfCharsToHide = endIndex - startIndex;
email.replace(startIndex, endIndex, "*".repeat(numOfCharsToHide));

Alphanumeric subtrings sorting [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I need to write a java code to covert VBA7425IWC to ABV2457CIW. I need help in that. If I sort the strings they sort by ASCII values and the numbers become one chunk and the alphabets another.
This one uses regex. You may have to adjust the pattern to include lower case letters:
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SplitRegex {
public static void main(String[] args) {
// The search string
String str = "VBA7425IWC";
// The Regular expression (Finds {word} tokens)
Pattern pt = Pattern.compile("[A-Z]+|[0-9]+");
// Match the string with the pattern
Matcher m = pt.matcher(str);
String result = "";
// If results are found
while (m.find()) {
char[] chArray = m.group(0).toCharArray();
Arrays.sort(chArray);
result += new String(chArray);
}
System.out.println(result);
}
}
Your question is a little vague in its requirements. Are you attempting to sort each individual substring of characters and numbers?
In that case, you need to determine the ranges of each substring, denoted by a shift from characters to numbers.
start = 0
current = 0
for current = 0 to string.length-1:
if ASCII of current is letter AND ASCII of next is number OR vice-versa:
sort(string, start, current)
start = current
You can find if a character is a letter or number by its ASCII value.
Here is sample solution which I achive by dividing string intro numeric and alphabetic substrings stored in List and then sorted and reduce with java 8 stream API.
String s = "VBA7425IWC";
List<String> mylist = new ArrayList<>();
StringBuilder subString = new StringBuilder();
for (int k = 0; k < s.length() - 1; k++) {
subString.append(s.charAt(k));
if ((Character.isDigit(s.charAt(k + 1))
&& Character.isAlphabetic(s.charAt(k))) ||
(Character.isDigit(s.charAt(k))
&& Character.isAlphabetic(s.charAt(k + 1)))) {
mylist.add(subString.toString());
subString.setLength(0);
}
}
mylist.add(subString.append(s.charAt(s.length() - 1)).toString());
System.out.println(mylist);
String finalResult = mylist
.stream()
.map((myString) -> {
char[] charArr = myString.toCharArray();
Arrays.sort(charArr);
return new String(charArr);
})
.reduce("", (s1, s2) -> s1 + s2);

Java Program, String [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
It's about string to make a compact output.
Example 1
Input : boooooob
Output : bob
Example2
Input : boobaabbiibbuuuuub
Output : bobabibub
Can anyone help me?
I'm stuck, thx.
This can be solved by using regular expression (\\w)\\1+
public class RemoveReplicateLetter {
public static void main(String[] args) {
//For input: boooooob
System.out.println(removeReplicateLetter("boooooob"));
//For input: boobaabbiibbuuuuub
System.out.println(removeReplicateLetter("boobaabbiibbuuuuub"));
}
public static String removeReplicateLetter(String word) {
/*
REGEX:
(\\w)\\1+
- \\w : matches any word character (letter, digit, or underscore)
- \\1+ : matches whatever was in the first set of parentheses, one or more times.
*/
return word.replaceAll("(\\w)\\1+", "$1");
//Here $1 means return letter with match in word by regex.
}
}
Output:
bob
bobabibub
This method should do the job:
public String simplify(String input) {
// Convert to an array for char based comparison
char[] inputArray = input.toCharArray();
// First char will always be included in the output because there is no char to compete
String output = String.valueOf(inputArray[0]);
// Check every char against the following
for (int i = 1; i < inputArray.length; i++) {
// If not equal
if (inputArray[i - 1] != inputArray[i]) {
// Add to output
output += inputArray[i];
}
}
// Return the result
return output;
}
It will compare every char with the following one and only adds it to the output if they are not equal.
Note: This is just a proof of concept, not an optimal solution.

how to create array from string in java with respective data items [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How to create an array from a string with two respective data items.
String str="USA*2*Japan*8^2*India*5^4^2*Germany*5*";
Here, I want to create an array of two items in .
Like this:
Arraylist<string> arr= [USA*2,Japan*8^2, India*5^4^2,Germany*5];
Here * is indicating main items and ^ is indicating sub items.
You are using the * to separate "main items" but it can also be inside the main item.
Your requirements look odd, but lets assume for the sake of argument that you are getting your input data like this and you want to split it like you suggested.
That means that every * that is preceded by a number is a separator, but a * that is not preceded by a number is not.
You can achieve that using regular expressions: (with a positive look-behind expression (?<=expr)
String str = "USA*2*Japan*8^2*India*5^4^2*Germany*5";
List<String> lst = Arrays.asList(Pattern.compile("(?<=\\d)\\*").split(str));
System.out.println(lst);
Prints:
[USA*2, Japan*8^2, India*5^4^2, Germany*5]
After further clarification in the comment below, it seems that the problem is more generic than the initial example; the question becomes:
How do I split a string on a separator, but only after 2 occurrences
of the separator.
Although it's possible to do with a regex, it may be easier to do and understand in a for loop like this:
public static List<String> split(String str, char splitChar, int afterOccurrences) {
List<String> lst = new ArrayList<>();
int occurrencesSeen = 0;
int start = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == splitChar) {
occurrencesSeen++;
if (occurrencesSeen >= afterOccurrences) {
lst.add(str.substring(start, i));
start = i + 1;
occurrencesSeen = 0;
}
}
}
if (start < str.length() - 1)
lst.add(str.substring(start));
return lst;
}
public static void main(String[] args) {
String str = "USA*2*Japan*8^2*India*5^4^2*Germany*5";
System.out.println(split(str, '*', 2));
}
This method also allows you to split after 3 or any other number of occurrences.

Categories