Count Delimiter in a string in Java - java

i have a string in Java.
1|2|3|4|5|2|2|3|4|123441|234556|67783|56764|55454
i want to count a delimiter above string. Please help me in how to count and i want only starting 7 Delimiter value.

You can split using | character.
public static void main(String[] args) {
String s = "1|2|3|4|5|2|2|3|4|123441|234556|67783|56764|55454";
String[] strArr = s.split("\\|");
System.out.println("Array : " + Arrays.toString(strArr));
System.out.println("Delimiter count : " + (strArr.length - 1)); // Prints 13
System.out.println("7th field : " + strArr[7]); // Prints 3
}

You can solve it with regular expressions, using Pattern and Matcher classes:
String s = "1|2|3|4|5|2|2|3|4|123441|234556|67783|56764|55454";
Pattern p = Pattern.compile("((\\d+\\|){7}).*");
Matcher m = p.matcher(s);
if (m.matches()) {
System.out.println(m.group(1));
}
To understand the code above, have a look at regular expressions, e.g. http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

In case if your input string if sthg like this:-
1|2|3|4|5|2|2|3|4|123441|234556|||
having empty values between delimiters. Then you can go with a different version of split function.
String[] strArr = s.split("\\|", -1);
You need to pass -1 as the second argument to split otherwise it removes empty strings.

Related

Need to get parameters alone from query as arraylist return parameter

I have written program which will take Query as input and to get parameters alone as arraylist return (used Regex patern Split) (OUTPUT)
but i am getting with () also if we added like its also coming.
Input
SELECT * FROM some_table
WHERE some_column1 = ‘%(some_parameter_1)%’ and
some_column2=’%(some_parameter_2)%’ and
some_column3=’%(some_parameter_3)%’;`
Output
An array list containing the following elements in it:
some_parameter_1
some_parameter_2
some_parameter_3
String patternString = "%";
Pattern pattern = Pattern.compile(patternString);
String[] split = pattern.split(query);
System.out.println("split.length = " + split.length);
for(String element : split){
System.out.println("element = " + element);
a1.add(element);
}
int n = a1.size();
for(int j =1;j <= n; j=j+2){
params.add(a1.get(j));
}
System.out.println("\n List of Parameters "+params);
/* for(int j =1;j <= 7; j=+1)
System.out.println(a1.get(j)); */
return params;
}
How to use match.result in regex? thats not getting effect it seems... or any other way to solve It.
I need the parameter alone enclosed in %(some-param1)% as a arraylist return.
Thanks in advance.
Your pattern, as well as your approach, will not lead you to your solution because using split,you will split on the pattern. Instead you want to match the pattern and extract the matched pattern.
For this, we can use the Pattern and Matcher class provided in java. The pattern which I have used (%\\()(.*?)(\\)%). Note \\ has been added for escaping
It has three section
1) (%\\() Search for a string starting with %(
2) (.*?) All the characters after the first one matched
3) (\\)%) Match till you find )% character.
Below is the sample working code for your example. Because we want to extract what is between %(...)% which is the second part, I have used group(2).
So matcher.group(1) will match %(, matcher.group(2) will match some_parameter_1 and matcher.group(3) will match )%. Doing it in a loop will parse the whole string and give all three parameters in ArrayList
public static void main(String[] args) {
String input = "SELECT * FROM some_table WHERE some_column1 = ‘%(some_parameter_1)%’ and some_column2=’%(some_parameter_2)%’ "
+ "and some_column3=’%(some_parameter_3)%’;";
Pattern pattern = Pattern.compile("(%\\()(.*?)(\\)%)");
Matcher matcher = pattern.matcher(input);
List<String> parameterList = new ArrayList<>();
while (matcher.find()) {
parameterList.add(matcher.group(2));
}
System.out.println(parameterList);
}

Parsing a string with [3:0] substring in it

I want to store two numbers from a string into two distinct variables - for example, var1 = 3 and var2 = 0 from "[3:0]". I have the following code snippet:
String myStr = "[3:0]";
if (myStr.trim().matches("\\[(\\d+)\\]")) {
// Do something.
// If it enter the here, here I want to store 3 and 0 in different variables or an array
}
Is it possible doing this with split and regular expressions?
Don't call trim(). Enhance you regex instead.
Your regex is missing the pattern for : and the second number, and you don't need to escape the ].
To capture the matched numbers, you need the Matcher:
String myStr = " [3:0] ";
Matcher m = Pattern.compile("\\s*\\[(\\d+):(\\d+)]\\s*").matcher(myStr);
if (m.matches())
System.out.println(m.group(1) + ", " + m.group(2));
Output
3, 0
You can use replaceAll and split
String myStr = "[3:0]";
if(myStr.trim().matches("\\[\\d+:\\d+\\]") {
String[] numbers = myStr.replaceAll("[\\[\\]]","").split(":");
}
Moreover, your regExp to match String should be \\[\\d+:\\d+\\], if you want to avoid trim you can add \\s+ at start and end to match the spaces.But trim is not bad.
EDIT
As suggested by Andreas in comments,
String myStr = "[3:0]";
String regExp = "\\[(\\d+):(\\d+)\\]";
Pattern pattern = Pattern.compile(regExp);
Matcher matcher = pattern.matcher(myStr.trim());
if(matcher.find()) {
int a = Integer.parseInt(matcher.group(1));
int b = Integer.parseInt(matcher.group(2));
System.out.println(a + " : " + b);
}
OUTPUT
3 : 0
Without any regular expressions you could do this:
// this will remove the braces [ and ] and just leave "3:0"
String numberString= myString.trim().replace("[", "").replace("]","");
// this will split the string in everything before the : and everything after the : (so two values as an array)
String[] numbers = numberString.split(":");
// get the first value and parse it as a number "3" will become a simple 3
int firstNumber = Integer.parseInt(numbers[0]) ;
// get the second value and parse it from "0" to a plain 0
int secondNumber = Integer.parseInt(numbers[1]);
be carefull when parsing numbers, depending on your input string and what other possibilities there might be (e.g. "3:12" is ok, but "3:02" might throw an error).
In case you don't need to validate input and you want to simply get numbers from it, you could simply find indexOf(":") and substring parts which you are interested, in which are:
from [ (which is at position 0) till :
and from index of : till ] (which is at position equal to length of string -1)
Your code can look like
String text = "[3:0]";
int colonIndex = text.indexOf(':');
String first = text.substring(1, colonIndex);
String second = text.substring(colonIndex + 1, text.length() - 1);

Splitting a string between a char

I want to split a String on a delimiter.
Example String:
String str="ABCD/12346567899887455422DEFG/15479897445698742322141PQRS/141455798951";
Now I want Strings as ABCD/12346567899887455422, DEFG/15479897445698742322141 like I want
only 4 chars before /
after / any number of chars numbers and letters.
Update:
The only time I need the previous 4 characters is after a delimiter is shown, as the string may contain letters or numbers...
My code attempt:
public class StringReq {
public static void main(String[] args) {
String str = "BONL/1234567890123456789CORT/123456789012345678901234567890HOLD/123456789012345678901234567890INTC/123456789012345678901234567890OTHR/123456789012345678901234567890PHOB/123456789012345678901234567890PHON/123456789012345678901234567890REPA/123456789012345678901234567890SDVA/123456789012345678901234567890TELI/123456789012345678901234567890";
testSplitStrings(str);
}
public static void testSplitStrings(String path) {
System.out.println("splitting of sprint starts \n");
String[] codeDesc = path.split("/");
String[] codeVal = new String[codeDesc.length];
for (int i = 0; i < codeDesc.length; i++) {
codeVal[i] = codeDesc[i].substring(codeDesc[i].length() - 4,
codeDesc[i].length());
System.out.println("line" + i + "==> " + codeDesc[i] + "\n");
}
for (int i = 0; i < codeVal.length - 1; i++) {
System.out.println(codeVal[i]);
}
System.out.println("splitting of sprint ends");
}
}
You claim that after / there can appear digits and alphabets, but in your example I don't see any alphabets which should be included in result after /.
So based on that assumption you can simply split in placed which has digit before and A-Z character after it.
To do so you can split with regex which is using look-around mechanism like str.split("(?<=[0-9])(?=[A-Z])")
Demo:
String str = "BONL/1234567890123456789CORT/123456789012345678901234567890HOLD/123456789012345678901234567890INTC/123456789012345678901234567890OTHR/123456789012345678901234567890PHOB/123456789012345678901234567890PHON/123456789012345678901234567890REPA/123456789012345678901234567890SDVA/123456789012345678901234567890TELI/123456789012345678901234567890";
for (String s : str.split("(?<=[0-9])(?=[A-Z])"))
System.out.println(s);
Output:
BONL/1234567890123456789
CORT/123456789012345678901234567890
HOLD/123456789012345678901234567890
INTC/123456789012345678901234567890
OTHR/123456789012345678901234567890
PHOB/123456789012345678901234567890
PHON/123456789012345678901234567890
REPA/123456789012345678901234567890
SDVA/123456789012345678901234567890
TELI/123456789012345678901234567890
If you alphabets can actually appear in second part (after /) then you can use split which will try to find places which have four alphabetic characters and / after it like split("(?=[A-Z]{4}/)") (assuming that you are using at least Java 8, if not you will need to manually exclude case of splitting at start of the string for instance by adding (?!^) or (?<=.) at start of your regex).
you can use regex
Pattern pattern = Pattern.compile("[A-Z]{4}/[0-9]*");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group());
}
Instead of:
String[] codeDesc = path.split("/");
Just use this regex (4 characters before / and any characters after):
String[] codeDesc = path.split("(?=.{4}/)(?<=.)");
Even simpler using \d:
path.split("(?=[A-Za-z])(?<=\\d)");
EDIT:
Included condition for 4 any size letters only.
path.split("(?=[A-Za-z]{4})(?<=\\d)");
output:
BONL/1234567890123456789
CORT/123456789012345678901234567890
HOLD/123456789012345678901234567890
INTC/123456789012345678901234567890
OTHR/123456789012345678901234567890
PHOB/123456789012345678901234567890
PHON/123456789012345678901234567890
REPA/123456789012345678901234567890
SDVA/123456789012345678901234567890
TELI/123456789012345678901234567890
It is still unclear if this is authors expected result.

Replacing regex with the same amount of "." as its length

See this for my current attempt: http://regexr.com?374vg
I have a regex that captures what I want it to capture, the thing is that the String().replaceAll("regex", ".") replaces everything with just one ., which is fine if it's at the end of the line, but otherwise it doesn't work.
How can I replace every character of the match with a dot, so I get the same amount of . symbols as its length?
Here's a one line solution:
str = str.replaceAll("(?<=COG-\\d{0,99})\\d", ".").replaceAll("COG-(?=\\.+)", "....");
Here's some test code:
String str = "foo bar COG-2134 baz";
str = str.replaceAll("(?<=COG-\\d{0,99})\\d", ".").replaceAll("COG-(?=\\.+)", "....");
System.out.println(str);
Output:
foo bar ........ baz
This is not possible using String#replaceAll. You might be able to use Pattern.compile(regexp) and iterate over the matches like so:
StringBuilder result = new StringBuilder();
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(inputString);
int previous = 0;
while (matcher.find()) {
result.append(inputString.substring(previous, matcher.start()));
result.append(buildStringWithDots(matcher.end() - matcher.start()));
previous = matcher.end();
}
result.append(inputString.substring(previous, inputString.length()));
To use this you have to define buildStringWithDots(int length) to build a String containing length dots.
Consider this code:
Pattern p = Pattern.compile("COG-([0-9]+)");
Matcher mt = p.matcher("Fixed. Added ''Show annualized values' chackbox in EF Comp Report. Also fixed the problem with the missing dots for the positions and the problem, described in COG-18613");
if (mt.find()) {
char[] array = new char[mt.group().length()];
Arrays.fill(array, '.');
System.out.println( " <=> " + mt.replaceAll(new String(array)));
}
OUTPUT:
Fixed. Added ''Show annualized values' chackbox in EF Comp Report. Also fixed the problem with the missing dots for the positions and the problem, described in .........
Personally, I'd simplify your life and just do something like this (for starters). I'll let you finish.
public class Test {
public static void main(String[] args) {
String cog = "COG-19708";
for (int i = cog.indexOf("COG-"); i < cog.length(); i++) {
System.out.println(cog.substring(i,i+1));
// build new string
}
}
}
Can you put your regex in grouping so replace it with string that matches the length of matched grouping? Something like:
regex = (_what_i_want_to_match)
String().replaceAll(regex, create string that has that many '.' as length of $1)
?
note: $1 is what you matched in your search
see also: http://www.regular-expressions.info/brackets.html

In Java how do you replace all instances of a character except the first one?

In Java trying to find a regular expression that will match all instances of a specific character (:) except the first instance, want to replace all instances except first with nothing.
I can do this,
Pattern p = Pattern.compile(":");
Matcher m = p.matcher(input);
String output = m.replaceAll("");
and there is also m.replaceFirst() but I want to replace everything but first.
Naive approach:
String[] parts = str.split(":", 2);
str = parts[0] + ":" + parts[1].replaceAll(":", "");
For regex replace use match pattern \G((?!^).*?|[^:]*:.*?): and as replacement use first group $1
See and test the regex code in Perl here.
public static void main(String[] args) {
String name ="1_2_3_4_5";
int index = name.indexOf("_");
String name1 = name.substring(index+1);
name1 = name1.replace("_", "#");
System.out.println(name.substring(0,index+1)+ name1);
}
You can use reg ex
String str1 = "A:B:C:D:E:F:G:H:I:J:K:L:M";
str1= str1.replaceAll("([:|_].*?):", "$1_");
str1= str1.replaceAll("([:|_].*?):", "$1_");
Here I cant modify the regex to have output in first replace itself. Actually first replaceAll do replace ':' with '_' in alternate positions.
if (matcher.find()) {
String start = originalString.substring(0, matcher.end());
matcher.reset(originalString.substring(matcher.end(), originalString.length()));
replacedString = start + matcher.replaceAll("");
}

Categories