How to extract the below pattern from a string? - java

I have a string which looks like below.
{(firstName1,lastName1,College1,{(24,25)},{(Street,23)},City1,Country1)}
I need to extract the details/values from the above and add them to a list. By details I mean:
["firstName1","lastName1","College1","24","25","Street","23","City1", "country1"]
How can I achieve the above? I tried the below method but not sure how to get all curly braces and brackets into the pattern.
private static String flattenPigBag(String pigdata) {
String s = "";
Pattern p = Pattern.compile("\\{(.*)}");
Matcher m = p.matcher(pigdata);
while (m.find()) {
s = m.group(1);
System.out.println("answer : " + s);
}
return s;
}

Try this:
String[] parts = str.replaceAll("}|\\{", "").split(",");

Are you forced to use a pattern? If not, feel free to use this.
private static List<String> flattenPigBag(String s) {
return Arrays.asList(s.replaceAll("[(){}]", "").split(","));
}
Output:
[firstName1, lastName1, College1, 24, 25, Street, 23, City1, Country1]

I assume you need to extract the individual fields for further processing. So here is what I would do. In my test program I just print out the fields, but I imagine in your program you may take those field values and use them somehow (e.g. apply them to some setters of a Java object)
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatchingWithNamedCaptureGroup {
public static void main(String[] args) {
String regex = "\\{(\\("
+ "(?<firstName>[^,]*)"
+ ",(?<lastName>[^,]*)"
+ ",(?<college>[^,]*)"
+ ",\\{\\("
+ "(?<num1>\\d*)"
+ ",(?<num2>\\d*)\\)\\}"
+ ",\\{\\((?<street>[^,]*)"
+ ",(?<streetNum>\\d*)\\)\\}"
+ ",(?<city>[^,]*)"
+ ",(?<country>[^,]*)"
+ "\\))\\}";
String input
= "{(firstName1,lastName1,College1,{(24,25)},{(Street,23)},City1,Country1)}";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if (m.find()) {
String firstName = m.group("firstName");
String lastName = m.group("lastName");
String college = m.group("college");
String num1 = m.group("num1");
String num2 = m.group("num2");
String street = m.group("street");
String streetNum = m.group("streetNum");
String city = m.group("city");
String country = m.group("country");
System.out.println(firstName
+ "," + lastName
+ "," + college
+ "," + num1
+ "," + num2
+ "," + street
+ "," + streetNum
+ "," + city
+ "," + country
);
} else {
System.err.println("Does not match!");
}
}
}
The output of this program is this:
firstName1,lastName1,College1,24,25,Street,23,City1,Country1

Related

Remove whitespace from start and end of String without trim()

How to remove whitespace from the start and end of a String without using the trim() method?
here is my code
public class StringTest {
public static void main(String[] args) {
String line = " Philippines| WNP|Naga |Camarines Sur|Naga Airport ";
//System.out.println(line);
int endIndex = line.indexOf("|");
String Country = line.substring(0, endIndex);
line = line.substring(endIndex + 1);
int endIndexCountry = line.indexOf("|");
String Code = line.substring(0, endIndexCountry);
line = line.substring(endIndexCountry + 1);
int endIndexCode = line.indexOf("|");
String City = line.substring(0, endIndexCode);
line = line.substring(endIndexCode + 1);
int endIndexCity = line.indexOf("|");
String State = line.substring(0, endIndexCity);
line = line.substring(endIndexCity + 1);
System.out.print("Code:" + Code + "____");
System.out.print("Country:" + Country + "____");
System.out.print("State:" + State + "____");
System.out.print("City:" + City + "____");
System.out.println("Airport:" + line+ "____");
}
}
and my output looks like this
Code: WNP____Country: Philippines____State:Camarines Sur____City:Naga ____Airport:Naga Airport ____
I need to look like this(without whitespaces)
Code:WNP____Country:Philippines____State:Camarines Sur____City:Naga____Airport:Naga Airport____
How to remove whitespace from the start and end of a String without
using the trim() method?
You can do it using a combination of regex patterns and String::replaceAll.
public class Main {
public static void main(String[] args) {
String str = " Hello ";
System.out.println("Before: " + str + "World!");
str = str.replaceAll("^[ \\t]+", "").replaceAll("[ \\t]+$", "");
System.out.println("After: " + str + "World!");
}
}
Output:
Before: Hello World!
After: HelloWorld!

parse filename using string [java]

What regex pattern do I need to parse a filename like this: "Ab12_Cd9023-2000-12-04-No234.nekiRtt3434GGG", where the parsed elements are: "Ab12_Cd9023"(name), "2000"(year), "12"(month), "04"(day), "234"(number), "nekiRtt3434GGG"(suffix). The sequence is always the same: name-yyyy-MM-dd-NoNN.suffix.
I want to use the pattern + matcher objects to solve that.
This is the most nice looking solution that I found:
private static final Pattern PATTERN = Pattern.compile("^(?<name>\\w+)-"
+ "(?<year>\\d{4})-"
+ "(?<month>\\d{2})-"
+ "(?<day>\\d{2})-"
+ "No(?<number>\\d+)."
+ "(?<suffix>\\w+)$");
Matcher m = PATTERN.matcher(file.getName());
if(!m.matches())
//some code if the pattern doesnt match
//this is how you acces the parsed strings:
m.group("year")
This regex should do the trick:
([a-bA-B0-9_])-([0-9]{4})-([0-9]{2})-([04]{2})-No(.+)\.(.+)$
If you use this as pattern, each of the () signifies one part of the string you want to capture.
This could work:
private static final Pattern PATTERN = Pattern.compile("^(.+)-([0-9]{4})-([0-9]{2})-([0-9]{2})-No(.+)\.(.+)$");
...
Matcher matcher = PATTERN.matcher(string);
if (matcher.matches()) {
String name = matcher.group(1);
int year = Integer.parseInt(matcher.group(2));
int month = Integer.parseInt(matcher.group(3));
int day = Integer.parseInt(matcher.group(4));
String number = matcher.group(5);
String suffix = matcher.group(6);
System.out.println("name: " + name);
System.out.println("year: " + year);
System.out.println("month: " + month);
System.out.println("day: " + day);
System.out.println("number: " + number);
System.out.println("suffix: " + suffix);
} else {
// error: does not match
}
If the sequence is always the same why not simply split it using - or . like this:
String filename = "Ab12_Cd9023-2000-12-04-No234.nekiRtt3434GGG";
String[] parts = filename.split("-|\\.");
for(String p : parts)
System.out.println(p);

Name Reversing in strings

Write a method lastNameFirst that takes a string containing a name such as "Harry Smith" or "Mary Jane Lee", and that returns the string with the last name first, such as "Smith, Harry" or "Lee, Mary Jane".
im supposed to check it against
http://wiley.code-check.org/codecheck/files?repo=bjlo2&problem=05_02
i post this
String firstName = name.substring(0, name.indexOf(" "));
String lastName = name.substring(name.indexOf(" "));
String cName = lastName + ", " + firstName;
if ( lastName == " " )
{
cName = firstName;
}
return cName;
I get 0/4 everytime please help im completely lost.
It might be simpler to create an array using the split function of the String class, then join them:
String cName = String.join(", ", Collections.reverse(Arrays.asList(name.split(" "))));
String.join is only in Java 8 I believe, if you're not using 8 you can use something like the following:
String[] names = name.split(" ");
String cName = names[1] + ", " + names[0];
You should also be using the equals method for comparing String and other objects:
String[] names = name.split(" ");
String cName = names[1].equals(" ") ? names[0] : names[1] + ", " + names[0];
Please try this code
String first = name.substring(name.lastIndexOf(" "));
String last = name.substring(0, name.lastIndexOf(" "));
String result = first + "," + last;
Your solution is very close. Here's 2 hints to get to the right solution:
What separates the first and last name is the last, not the first space (consider using str.lastIndexOf(" ")).
As mentioned in the comments, when comparing strings, you can't use str1 == str2, you have to use str1.equals(str2)
You only need the last space in your name, which you can get with String.lastIndexOf(int). Then you test if that is less then 0, if so return the input name. Otherwise, concatenate and return your name in the desired format. Using a ternary (or conditional operator ? :) that might look something like,
int p = name.lastIndexOf(' ');
return (p < 0) ? name : name.substring(p + 1) + ", " + name.substring(0, p);
I put this for that Question and it passed all 4 tests they had.
public static String lastNameFirst(String name)
{
String LastToFirst = "";
if(!name.contains(" ")){
return name;
}
int index = name.indexOf(" ");
int secondIndex = name.indexOf(" ", index + 1);
// exclusive of last index
if(secondIndex != -1) {
LastToFirst += name.substring(secondIndex+1,name.length())+", ";
LastToFirst += name.substring(0,secondIndex);
}
else {
LastToFirst += name.substring(index +1,name.length()) + ", ";
LastToFirst += name.substring(0, index);
return LastToFirst;
}
A better solution for this would be to use an array, and store the characters in there and for the spacing one should add an index variable for where you want the splitting to happen- the string of interest. The solutions above do a good example of expalining this better, they consider cases where it is not a white space, but other symbols making the method more robust. Hope this helps.
I tried this code and all the four arguement works. Hope this helps!!
{
String[] names = name.split(" ");
String cName = "";
if(names.length > 2){
cName = names[2].equals(" ") ? names[0] : names[2] + ", " + names[0] + " " + names[1];
}
else if(names.length == 1){
cName = names[0]
}
else{
cName = names[1].equals(" ") ? names[0] : names[1] + ", " + names[0];
}
return cName;
}
}
public class Names
{
/**
Changes a name so that the last name comes first.
#param name a name such as "Mary Jane Lee"
#return the reversed name, such as "Lee, Mary Jane".
If name has no spaces, it is returned without change.
*/
public static String lastNameFirst(String name)
{
String result = "";
if(!name.contains(" "))
{
String firstOnly = name.substring(0);
return firstOnly;
}
else
{
String first = name.substring(name.lastIndexOf(" ")+1);
String last = name.substring(0, name.lastIndexOf(" "));
result = first + ", " + last;
return result;
}
}
}
This is the correct answer that will get you 4/4.

simple string concat manipulation in java

I want to get the following output:
Hello Steve Andrews!
These are my variables:
a = "steve";
b = "Andrew"
I tried this:
System.out.print("Hello " + a + " " + b + "s");
I don't know where to put .toUpper() for steve. The s should be in uppercase. How do I do this?
Use StringUtils.capitalize(a),
"Hello " + StringUtils.capitalize(a) + " " + b + "s"
Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char). No other letters are changed.
You could use StringUtils.capitalize(str), or if you want to do it by yourself:
public static String capitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuffer(strLen)
.append(Character.toTitleCase(str.charAt(0)))
.append(str.substring(1))
.toString();
}
You could also try using this method:
public static String capitalize(String str) {
str = (char) (str.charAt(0) - 32) + str.substring(1);
return str;
}
Though it should be noted that this method assumes that the first character in str is indeed a lowercase letter.
Finally, I tried to do it without stringutils.. But anyways, thanks to all who helped :)
public class Hello
{
public static void main(String[] args){
String a = "steve";
String b = "Andrew";
String firstletter = a.substring(0,1);
String remainder = a.substring(1);
String capitalized = firstletter.toUpperCase() + remainder.toLowerCase();
System.out.print("Hello " + capitalized + " " + b + "s" );
}
}

Regular expression in java to replace a pattern in multiple lines

I want to replace this file input to a html table:
ip add St Stat Type Mode ip only class numbers
------------------------------ -- ----- ---- ---- --------------- ------ -----
ABC_127.562.200.5/32 - up ABC - 127.562.200.5 5
ABC_127.292.200.3/32 - up ABC - 127.562.200.5 4
ABC_127.262.200.13/32 - up ABC - 127.562.200.5 3
ABC:jdnsajkds
I know this will end with "ABC" but I am not able to figure out why "/" is also coming in input
import java.util.regex.*;
interface LogExample {
public static final int NUM_FIELDS = 7;
public static final String logEntryLine = "ABC_127.562.200.5/32 **space** -- **space** up **space** ABC **space** -- **space** 127.562.200.5 **space** 5 **space** ";
}
public class LogRegExp implements LogExample {
public static void main(String argv[]) {
String logEntryPattern = "";//thats i am not getting
System.out.println("Using RE Pattern:");
System.out.println(logEntryPattern);
System.out.println("Input line is:");
System.out.println(logEntryLine);
Pattern p = Pattern.compile(logEntryPattern);
Matcher matcher = p.matcher(logEntryLine);
if (!matcher.matches() ||
NUM_FIELDS != matcher.groupCount()) {
System.err.println("Bad log entry (or problem with RE?):");
System.err.println(logEntryLine);
return;
}
System.out.println("name + IP Address: " + matcher.group(1));
System.out.println("status1: " + matcher.group(2));
System.out.println("status2: " + matcher.group(3));
System.out.println("type: " + matcher.group(4));
System.out.println("mode: " + matcher.group(5));
System.out.println("IP Address: " + matcher.group(6));
System.out.println("class: " + matcher.group(7));
System.out.println("numbers: " + matcher.group(8));
}
}
Since your class column is blank, we can't do very much to extract that information. But this regex will match the 7 columns of data that you do have:
String logEntryPattern = "(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)";
We need to escape the backslash in the Java string literal.
System.out.println("name + IP Address: " + matcher.group(1));
System.out.println("status1: " + matcher.group(2));
System.out.println("status2: " + matcher.group(3));
System.out.println("type: " + matcher.group(4));
System.out.println("mode: " + matcher.group(5));
System.out.println("IP Address: " + matcher.group(6));
System.out.println("numbers: " + matcher.group(7));
Frankly, a regular expression is a little much for what you're trying to so -- just tokenizing on spaces would work just as well -- but it gets the job done.
I got the solution:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] )
{
// String to be scanned to find the pattern.
// String line = "MSEM-E-031_TO_RVBC-R-001_T1 en up TE ingr 124.252.200.2 ELSP 0";
// String pattern = "((\\-{8})+.*?)";
String line = "ADR-SSF-1008-M008 vlan en dn 10081008";
String pattern = "((\\-{6})+.*?)";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(line);
if (m.find( ))
{
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
}
else
{
System.out.println("NO MATCH");
}
}
}

Categories