I want to split this string (1,0) and get result 1 and 0 i have tried this code:
String str ="(1,0)";
String parts[]= str.split("(,)");
System.out.println(parts[0]);
System.out.println(parts[1]);
But i got this :
(1
0)
Here's an efficient way you can isolate all your digits using the Regex Tools and put them into an ArrayList for easy usage. It doesn't use the .split() method, but it is efficient.
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public static void main(String[] args) {
String str = "(1,0)";
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(str);
ArrayList<Integer> vals = new ArrayList<>();
while(m.find())
vals.add(Integer.parseInt(m.group()));
System.out.println(vals);
}
A simple solution would be as follows:
public class Main {
public static void main(String[] args) {
String str = "(1,0)";
String parts[] = str.replace("(", "").replace(")", "").split(",");
System.out.println(parts[0]);
System.out.println(parts[1]);
}
}
Output:
1
0
If you split on (, the first value in the returned array will be "".
I'd recommend using regex directly, e.g.
String input = "(1,0)";
Matcher m = Pattern.compile("\\(([^,\\)]+),([^,\\)]+)\\)").matcher(input);
if (! m.matches())
throw new IllegalArgumentException("Invalid input: " + input);
System.out.println(m.group(1));
System.out.println(m.group(2));
Of course, if you insist on using split(), it can be done like this:
String input = "(1,0)";
String[] parts = input.split("[(,)]");
if (parts.length != 3 || ! parts[0].isEmpty())
throw new IllegalArgumentException("Invalid input: " + input);
System.out.println(parts[1]);
System.out.println(parts[2]);
If you know how to use regex, go for that. (personally I prefer to use string manipulation here because it's really easier) If not, learn how to use it or do something like this:
String input = "(64,128)";
String[] numbers = input.substring(1, input.length() - 1).split(",");
Try this, assuming your format is consistent.
String str = "(1,0)";
String[] tokens = str.substring(1,str.length()-1).split(",");
System.out.println(Arrays.toString(tokens));
Prints
[1, 0]
or if printed separately
1
0
Related
I try to extract string values from this string:
String str = "[{\"name:\"s2\"},{},{\"name\":\"f2\"},{\"name\":\"f2\"},{},{\"name\":\"l\"}]";
I use regex to extract "s2", "f2", "f2" and "l".
I thought about a solutions, define a regex to find string that begin with ":" + a quotation mark and end with a quotation mark.
I'm not very familiar with regex but I assumed my regex would look like something like this ? ":\".?\""
public static void main(String... args) {
Pattern p = Pattern.compile(":\".?\"");
String str = "[{\"name:\"s2\"},{},{\"name\":\"f2\"},{\"name\":\"f2\"},{},{\"name\":\"l\"}]";
Matcher m = p.matcher(str);
System.out.println(str);
while (m.find()) {
System.out.println("groupe = " + m.group());
}
}
Thanks for your help.
Use can use this pattern:
"(?<=:")[^"]*"
See Demo
I am getting comma sepeated string in below format:
String codeList1 = "abc,pqr,100101,P101001,R108972";
or
String codeList2 = "mno, 100101,108972";
Expected Result : Check if code is numeric after removing first alphabet. If yes, remove prefix and return. If no, still return the code.
codeList1 = "abc,pqr,100101,101001,108972";
or
codeList2 = "mno, 100101,108972";
As you can see, I can get codes (P101001 or 101001) and (R108972 ,108972) format. There is will be only one prefix only.
If I am getting(P101001), I want to remove 'P' prefix and return number 101001.
If I am getting 101001, do nothing.
Below is the working code. But is there any easier or more efficient way of achieving this. Please help
for (String code : codeList.split(",")) {
if(StringUtils.isNumeric(code)) {
codes.add(code);
} else if(StringUtils.isNumeric(code.substring(1))) {
codes.add(Integer.toString(Integer.parseInt(code.substring(1))));
} else {
codes.add(code);
}
}
If you want to remove prefixes from the numbers you can easilly use :
String[] codes = {"abc,pqr,100101,P101001,R108972", "mno, 100101,108972"};
for (String code : codes){
System.out.println(
code.replaceAll("\\b[A-Z](\\d+)\\b", "$1")
);
}
Outputs
abc,pqr,100101,101001,108972
mno, 100101,108972
If you are using Java 8+, and want to extract only the numbers, you can just use :
String codeList1 = "abc,pqr,100101,P101001,R108972";
List<Integer> results = Arrays.stream(codeList1.split("\\D")) //split with non degits
.filter(c -> !c.isEmpty()) //get only non empty results
.map(Integer::valueOf) //convert string to Integer
.collect(Collectors.toList()); //collect to results to list
Outputs
100101
101001
108972
You can use regex to do it
String str = "abc,pqr,100101,P101001,R108972";
String regex = ",?[a-zA-Z]{0,}(\\d+)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
while(matcher.find()){
System.out.println(matcher.group(1));
}
Output
100101
101001
108972
Updated:
For your comment(I want to add add the codes. If single alphabet prefix found , remove it and add remaining ),you can use below code:
String str = "abc,pqr,100101,P101001,R108972";
String regex = "(?=,?)[a-zA-Z]{0,}(?=\\d+)|\\s";// \\s is used to remove space
String[] strs = str.replaceAll(regex,"").split(",");
Output:
abc
pqr
100101
101001
108972
How about this:
String codeList1 = "abc,pqr,100101,P101001,R108972";
String[] codes = codeList1.split(",");
for (String code : codes) {
if (code.matches("[A-Z]?\\d{6}")) {
String codeF = code.replaceAll("[A-Z]+", "");
System.out.println(codeF);
}
}
100101
101001
108972
Demo
from the String value want to getting word before and after the <in>
String ref = "application<in>rid and test<in>efd";
int result = ref.indexOf("<in>");
int result1 = ref.lastIndexOf("<in>");
String firstWord = ref.substring(0, result);
String[] wor = ref.split("<in>");
for (int i = 0; i < wor.length; i++) {
System.out.println(wor[i]);
}
}
my Expected Output
String[] output ={application,rid,test,efd}
i tried with 2 Option first one IndexOf but if the String have more than two <in>i 'm not getting my expected output
Second One splitits also not getting with my expected Output
please suggest best option to getting the word(before and after <in>)
You could use an expression like so: \b([^ ]+?)<in>([^ ]+?)\b (example here). This should match the string prior and after the <in> tag and place them in two groups.
Thus, given this:
String ref = "application<in>rid and test<in>efd";
Pattern p = Pattern.compile("\\b([^ ]+?)<in>([^ ]+?)\\b");
Matcher m = p.matcher(ref);
while(m.find())
System.out.println("Prior: " + m.group(1) + " After: " + m.group(2));
Yields:
Prior: application After: rid
Prior: test After: efd
Alternatively using split:
String[] phrases = ref.split("\\s+");
for(String s : phrases)
if(s.contains("<in>"))
{
String[] split = s.split("<in>");
for(String t : split)
System.out.println(t);
}
Yields:
application
rid
test
efd
Regex is your friend :)
public static void main(String args[]) throws Exception {
String ref = "application<in>rid and test<in>efd";
Pattern p = Pattern.compile("\\w+(?=<in>)|(?<=<in>)\\w+");
Matcher m = p.matcher(ref);
while (m.find()) {
System.out.println(m.group());
}
}
O/P :
application
rid
test
efd
No doubt matching what you need using Pattern/Matcher API is simpler for tis problem.
However if you're looking for a short and quick String#split solution then you can consider:
String ref = "application<in>rid and test<in>efd";
String[] toks = ref.split("<in>|\\s+.*?(?=\\b\\w+<in>)");
Output:
application
rid
test
efd
RegEx Demo
This regex splits on <in> or a pattern that matches a space followed by 0 more chars followed by a word and <in>.
You can also try the below code, it is quite simple
class StringReplace1
{
public static void main(String args[])
{
String ref = "application<in>rid and test<in>efd";
System.out.println((ref.replaceAll("<in>", " ")).replaceAll(" and "," "));
}
}
I need to find the length of my string "பாரதீய ஜனதா இளைஞர் அணி தலைவர் அனுராக்சிங் தாகூர் எம்.பி. நேற்று தேர்தல் ஆணையர் வி.சம்பத்". I got the string length as 45 but i expect the string length to be 59. Here i need to add the regular expression condition for spaces and dot (.). My code
import java.util.*;
import java.lang.*;
import java.util.regex.*;
class UnicodeLength
{
public static void main (String[] args)
{
String s="பாரதீய ஜனதா இளைஞர் அணி தலைவர் அனுராக்சிங் தாகூர் எம்பி நேற்று தேர்தல் ஆணையர் விசம்பத்";
List<String> characters=new ArrayList<String>();
Pattern pat = Pattern.compile("\\p{L}\\p{M}*");
Matcher matcher = pat.matcher(s);
while (matcher.find()) {
characters.add(matcher.group());
}
// Test if we have the right characters and length
System.out.println(characters);
System.out.println("String length: " + characters.size());
}
}
The code below worked for me. There were three issues that I fixed:
I added a check for spaces to your regular expression.
I added a check for punctuation to your regular expression.
I pasted the string from your comment into the string in your code. They weren't the same!
Here's the code:
public static void main(String[] args) {
String s = "பாரதீய ஜனதா இளைஞர் அணி தலைவர் அனுராக்சிங் தாகூர் எம்.பி. நேற்று தேர்தல் ஆணையர் வி.சம்பத்";
List<String> characters = new ArrayList<String>();
Pattern pat = Pattern.compile("\\p{P}|\\p{L}\\p{M}*| ");
Matcher matcher = pat.matcher(s);
while (matcher.find()) {
characters.add(matcher.group());
}
// Test if we have the right characters and length
int i = 1;
for (String character : characters) {
System.out.println(String.format("%d = [%s]", i++, character));
}
System.out.println("Characters Size: " + characters.size());
}
It's probably worth pointing out that your code is remarkably similar to the solution for this SO. One comment on that solution in particular led me to discover the missing check for punctuation in your code and allowed me to notice that the string from your comment didn't match the string in your code.
How can i split 100.26kg to System.out.println as
100.26
kg
I tried doing by using ("\d+") but was not successful.
String[] num = myTextCount.split("\\d+");
The 100.26kg may vary according to user input. It could be 100.26kg, 100g, 100 pounds or 100litre. If there is any way to split the number and alphabet, it will be very helpful
myTextCount.split("[\\.\\d]+") will give you [, kg] which contain the second part, and then use #indexOf() to find the first part.
Try look-around regex,
String[] num = myTextCount.split("(?<=\\d)(?=[a-z])|(?<=[a-z])(?=\\d)");
If you want to split case-insensitive with number than use (?i)
String[] num = myTextCount.split("(?i)(?<=\\d)(?=[a-z])|(?<=[a-z])(?=\\d)");
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
String inputs[] = { "100.26kg", "100g", "100 pounds", "100litre"};
String weight, unit;
for(String input : inputs){
Scanner scan = new Scanner(input);
weight = scan.findInLine("\\d+(\\.\\d+)?");
unit = scan.next();//scan.next("\\w+");
System.out.println(weight);
System.out.println(unit);
}
}
}
Do not use Split, just use the String.IndexOf() function to deal with it.
Matcher m = Pattern.compile("^([0-9.]+)\\s*([a-zA-Z]+)$").matcher("");
String inputs[] = {"100.26kg", "1 pound", "98gallons" };
for(String input: inputs)
{
if ( m.reset(input).find() )
{
System.out.printf("amount=[%s] unit=[%s]\n", m.group(1), m.group(2) );
}
}
yields:
amount=[100.26] unit=[kg]
amount=[1] unit=[pound]
amount=[98] unit=[gallons]
Try this:
private static final Pattern VALID_PATTERN = Pattern.compile("[0-9]+|[A-Z]+");
private List<String> parse(String toParse) {
List<String> chunks = new LinkedList<String>();
Matcher matcher = VALID_PATTERN.matcher(toParse);
while (matcher.find()) {
chunks.add( matcher.group() );
}
return chunks;
}
This solution is quite modular as well.