I have input string array containing value like
1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0
What could be the best way to obtain values out of above input which contains 1950/00/00,
1953/00/00, 1958/00/00 , 1960/00/00 and 1962/0 in individual string objects?
Use the method String.split(regex):
String input = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0";
String[] parts = input.split(";");
for (String part : parts) {
System.out.println(part);
}
The split() method splits the string based on the given regular expression or delimiter, and returns the tokens in the form of array. Below example shows splitting string with (;)
public class MyStrSplit {
public static void main(String a[]){
String str = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0";
String[] tokens = str.split(";");
for(String s:tokens){
System.out.println(s);
}
}
}
Another choice to split string by regular expression:
public class SpitByRegx
{
public static void main(String[] args)
{
String input = "1950/00/00;1953/00/00;1958/00/00;1960/00/00;1962/0";
Pattern pattern = Pattern.compile("([0-9/]+);?");
Matcher m = pattern.matcher(input);
while(m.find())
{
System.out.println(m.group(1));
}
}
}
Related
replace or remove special char from List java
List<String> somestring = ['%french',
'#spanish',
'!latin'];
How to remove the special characters and replace it with space.
List<String> somestring = ['%french',
'#spanish',
'!latin'];
somestring.replaceall('%','');
How to get this as result
List<String> somestring = ['french',
'spanish',
'latin'];
First, never use a raw List. You have a List<String>. Second, a String literal (in Java) is surrounded by double quotes (") not single quotes. Third, you can stream your List<String> and map the elements with a regular expression and collect them back to the original List<String>. Like,
List<String> somestring = Arrays.asList("%french", "#spanish", "!latin");
somestring = somestring.stream().map(s -> s.replaceAll("\\W", ""))
.collect(Collectors.toList());
System.out.println(somestring);
Outputs (as requested)
[french, spanish, latin]
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches {
private static String REGEX = "\\!|\\%|\\#"; //control on Special characters...
private static String INPUT = "The %dog% says !meow. " + "!All #dogs #say meow.";
private static String REPLACE = ""; //Replacement string
public static void main(String[] args) {
Pattern p = Pattern.compile(REGEX);
//get a matcher object
Matcher m = p.matcher(INPUT);
INPUT = m.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
Added a sample snippet to explain the same, please extend to collections accordingly.
I need to create some kind of translator. I have a HashMap with pairs of Russian and English words as keys and values respectively. When I input a phrase in Russian I need to get English translation or nulls/not found for the words which are not in the dictionary.
So I have such methods for translation:
public boolean isInDictionary(String word){
if(dictionary.containsKey(word)){
return true;
}
return false;
}
public String translateSentence(String sentence){
StringBuilder result = new StringBuilder();
String[] splittedStrings = sentence.split( "\n" );
List<String> list = new ArrayList<>();
for(String s : splittedStrings){
result.append(translateCheck(s));
}
return result.toString();
}
public String getWord(String word){
return dictionary.get(word);
}
Here is how I call these methods:
Scanner scanner = new Scanner(System.in);
Translator translator = new Translator();
System.out.println("Input the phrase to translate:");
String input = scanner.nextLine();
System.out.println(translator.translateSentence(input));
When I input distinct word in Russian I get a translation for that, while when I input a phrase consisting of different words I get null.
So what am I doing wrong? I would be grateful for some help!
Something like this:
public boolean isInDictionary(String word) {
return dictionary.containsKey(word); //note the removal of the if as it already returns a boolean
}
public String translateSentence(String sentence) {
StringBuilder result = new StringBuilder();
String[] splittedStrings = sentence.trim().split(" "); // the actual change
List<String> list = new ArrayList<>();
for (String s : splittedStrings) {
result.append(translateCheck(s));
}
return result.toString();
}
public String getWord(String word) {
return dictionary.get(word);
}
You are splitting the sentence by lines instead of words, probably you wanted to use sentence.split(" ") instead of sentence.split("\n").
Simple scenario but finding difficult to finish off -
my string is -
String ipAdd = "["2.2.2.2","1.1.1.1","6.6.6.6","4.4.4.4"]"
I want to have all elements in an array list. How can I do that?
I try pattern matching for IP and all, not working and by using split function, it includes quotes and bracket.
Using replaceAll() (to remove braces) and split() (to split based on comma) should work :
public static void main(String... args) throws Exception {
String ipAdd = "[\"2.2.2.2\",\"1.1.1.1\",\"6.6.6.6\",\"4.4.4.4\"]";
List<String> list = Arrays.asList(ipAdd.replaceAll("\\[|\\]", "").split(","));
for (String s : list){
System.out.println(s);
}
}
O/P :
"2.2.2.2"
"1.1.1.1"
"6.6.6.6"
"4.4.4.4"
The following code maybe fulfill your requirement:
public static void main(String[] args) {
String st = "[\"2.2.2.2\",\"1.1.1.1\",\"6.6.6.6\",\"4.4.4.4\"]";
String patternString1 = "(\\d\\.\\d\\.\\d\\.\\d)";
Pattern pattern = Pattern.compile(patternString1);
Matcher matcher = pattern.matcher(st);
ArrayList<String> list = new ArrayList<>();
while(matcher.find()) {
list.add(matcher.group(1));
}
for (String item : list) {
System.out.println("" + item);
}
}
You can use regular expression with capturing groups to extract the IP from the string. (refer to https://docs.oracle.com/javase/tutorial/essential/regex/groups.html)
Could somebody tell me if a Java equivalent exist for PHP preg_grep()? Or supply me with a good way to accomplish the same?
I need to do string matching against element in input array and return array with input array's indexes as preg_grep() does.
There is no exact equivalent. But you can use the String#matches(String) function to test if a string matches a given pattern. For example:
String s = "stackoverflow";
s.matches("stack.*flow"); // <- true
s.matches("rack.*blow"); // <- false
If you want a result array with the matching indices, you can loop over your given input array of strings, check for a match and add the current index of the loop to your result array.
You could use this kind of function, using String.matches() and iterating over your array :
public static List<Integer> preg_grep(String pattern, List<String> array)
{
List<Integer> indexes = new ArrayList<Integer>();
int index = 0;
for (String item : array) {
if (item.matches("ba.*")) {
indexes.add(index);
}
++index;
}
return indexes;
}
Ideone Example
How about something like:
private static String[] filterArrayElem(String[] inputArray) {
Pattern pattern = Pattern.compile("(^a.*)");
List<String> resultList = new ArrayList<>();
for (String inputStr : inputArray) {
Matcher m = pattern.matcher(inputStr);
if (m.find()) {
resultList.add(m.group(0));
}
}
return resultList.toArray(new String[0]);
}
You can then use it in the following way:
String [] input = { "apple", "banana", "apricot"};
String [] result = filterArrayElem(input);
import java.util.ArrayList;
import java.util.StringTokenizer;
public class test {
public static void main(String args[]) {
ArrayList<String> data = new ArrayList<String>();
String s = "a,b,c,d,e,f,g";
StringTokenizer st = new StringTokenizer(s,",");
while(st.hasMoreTokens()){
data.add(st.nextToken());
}
System.out.println(data);
}
}
Problem in finding empty elements in a CSV data
the above code works well when the data is complete. If some data is missing it fails to detect the empty data.
ex:
Complete DATA : a,b,c,d,e,f,g
if a,d,e,g are removed
New DATA : ,b,c,,,f,
4 data missing!!
I need a way to put this data into ArrayList with null or "" values for empty data
You can use Guava Splitter to do that:
import com.google.common.base.Splitter;
public class Example
{
private static final Splitter SPLITTER = Splitter.on(",").trimResults();
public List<String> split(String singleLine) {
return SPLITTER.split(singleLine);
}
}
I'm sure there are more elegant solutions, but a simple one would be to use split() function:
public static void main(String args[]) {
ArrayList<String> data = new ArrayList<String>();
String s = ",b,c,,,f,";
//create an array of strings, using "," as a delimiter
//if there is no letter between commas, an empty string will be
//placed in strings[] instead
String[] strings = s.split(",", -1);
for (String ss : strings) {
data.add(ss);
}
System.out.println(data);
}