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");
}
}
}
Related
I have the following code, trying to match pyramids of increasing * count, surrounded by an equivalent number of spaces on either side.
//pyramid
var p = " * \n" +
" *** \n" +
" ***** \n" +
" ******* \n" +
" ********* \n" +
"***********\n";
//not a pyramid - rows 2 and 3 do not increase in width
var np = " * \n" +
" ***** \n" +
" ***** \n" +
" ******* \n" +
" ********* \n" +
"***********\n";
//pyramid with more width variation, non-point top
var pspace = " ** \n" +
" **** \n" +
" ********** \n" +
" ************** \n" +
" **************** \n" +
"**********************\n";
final var REGEX = "((?<S>\\s*)(?<star>\\**)\\k<S>\\R(?=$|((?<S2>\\s*)(?<extra>\\*+)\\k<star>\\k<extra>\\k<S2>\\R)))+";
System.out.println("p is a pyramid: "+Pattern.matches(REGEX, p));
System.out.println("np is a pyramid: "+Pattern.matches(REGEX, np));
System.out.println("pspace is a pyramid: "+Pattern.matches(REGEX, pspace));
Output:
p is a pyramid: true
np is a pyramid: false
pspace is a pyramid: true
The final thing I want to do is make sure that all "lines" of the input string are of equal length. At this point, I got completely stuck, as I couldn't really find anything but fixed-length String bounds (i.e. X{min, max}). So, here's what I'm wondering:
How can I make sure that all the lines within my string are pyramids (increasing number of stars from first line to last line (done), separated by new lines (done), centered within the spaces (done), and equal length lines (???))?
How can I simplify my regex to reduce the overuse of named capturing groups?
Regular expressions are incapable of doing the type of counting you are trying to accomplish, so you have to use a mixed strategy. Break up the string on newline boundaries then use a regular expression to match the leading and trailing spaces and the asterisks between them. But you will then have to see if the lengths of these matches meet your requirements by seeing how long these strings are using the length method that String objects possess:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class test
{
public static void main(String[] args) {
String p = " * \n" +
" *** \n" +
" ***** \n" +
" ******* \n" +
" ********* \n" +
"***********\n";
String[] lines = p.split("\n");
Pattern pattern = Pattern.compile("^(\\s*)(\\*+)(\\s*)$");
int lastLength = 0;
boolean isPyramid = true;
for (String line : lines) {
Matcher m = pattern.matcher(line);
m.find();
String spaces1 = m.group(1);
String spaces2 = m.group(3);
String asterisks = m.group(2);
int len = asterisks.length();
if (len <= lastLength || spaces1.length() != spaces2.length()) {
isPyramid = false;
break;
}
else {
lastLength = len;
}
}
System.out.println("p is a pyramid: " + isPyramid);
}
}
I can have string like switchaubcsp-loafsyvgvhv which can possibly contain any of the following patterns: s-loaf, p-loaf etc.
Following is the requirement in detail:
1st character - Any of [p,s,a,r,l],
2nd character -> [-], Followed by Word [loaf].
In the above example, when searched for [p-loaf], Found the text p-loaf starting at 11 index and ending at index 17 using java.util.regex.
What will be the regular expression for finding the first character to be Any of [p,s,a,r,l], 2nd character -> [-], Followed by Word [loaf].
[psarl]-loaf
if you want the word to start with it, add ^ to the beginning and if you want the word to end with it, add $ to the end.
you can try it out here demo regex
import java.util.regex.*;
public class RegexExamples {
public static void main(String[] args) {
RegexTag("devicexyzas-loafcdbdd", "[psarl][-]loaf");
}
public static void RegexTag(Stri`enter code here`ng Content, String PatternToMatch){
Pattern pattern;
try {
pattern = Pattern.compile(PatternToMatch);
}
catch (PatternSyntaxException e)
{
System.err.println ("Regex syntax error: " + e.getMessage ());
System.err.println ("Error description: " + e.getDescription ());
System.err.println ("Error index: " + e.getIndex ());
System.err.println ("Erroneous pattern: " + e.getPattern ());
return;
}
Matcher matcher = pattern.matcher(Content);
System.out.println ("Regex = " + Content);
System.out.println ("Text = " + PatternToMatch);
System.out.println ();
while (matcher.find()) {
System.out.println("Found the text \"" + matcher.group()
+ "\" starting at " + matcher.start()
+ " index and ending at index " + matcher.end());
}
}
}
I am trying to add all of the output records from a regex parsed txt file to one JOptionPane window. I have created a string to capture, but mine continues to print individual windows. Any ideas? Thanks
while ((line = br.readLine()) != null) {
if (Pattern.matches(titlePattern, line)) {
String name = "", price="";
String patternName = "title=\".*?(\")";
Pattern r = Pattern.compile(patternName);
Matcher m = r.matcher(line);
if (m.find( )) {
name = m.group(0);
//System.out.println("Title: " + name.substring(7, name.length()-1));
}
String patternPrice = "Suggested Retail Price:.*?\"";
String strOutput;
r = Pattern.compile(patternPrice);
m = r.matcher(line);
if (m.find( )) {
price = m.group(0);
//System.out.println("Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1));
//JOptionPane.showMessageDialog(null, "Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1));
final_list.addElement("Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1));
strOutput = "Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1);
JOptionPane.showMessageDialog(null, strOutput);
}
}
}
Try to use java.swing.TextArea to build message and JOptionPane to display it. Here is short demo:
public static void main(String[] args) {
TextArea textView = new TextArea();
textView.append("dsddd");
textView.append("jsdjsd");
textView.append("qwoqwo");
JOptionPane.showMessageDialog(null, textView);
}
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
I've been trying to replace this mathematical function x^2*sqrt(x^3) to this pow(x,2)*Math.sqrt(pow(x,3))
so this is the regex
/([0-9a-zA-Z\.\(\)]*)^([0-9a-zA-Z\.\(\)]*)/ pow(\1,\2)
it works in ruby, but I can't find a way to do it in java, I tried this method
String function= "x^2*sqrt(x^3)";
Pattern p = Pattern.compile("([a-z0-9]*)^([a-z0-9]*)");
Matcher m = p.matcher(function);
String out = function;
if(m.find())
{
System.out.println("GRUPO 0:" + m.group(0));
System.out.println("GRUPO 1:" + m.group(1));
out = m.replaceFirst("pow(" + m.group(0) + ", " + m.group(1) + ')');
}
String funcformat = out;
funcformat = funcformat.replaceAll("sqrt\\(([^)]*)\\)", "Math.sqrt($1)");
System.out.println("Return Value :"+ funcion );
System.out.print("Return Value :"+ funcformat );
But still doesn´t work, the output is: pow(x, )^2*Math.sqrt(x^3) as I said before it should be pow(x,2)*Math.sqrt(pow(x,3)).
Thank you!!
As others have commented, regex is not the way to go. You should use a parser. But if you want some quick and dirty:
From Matcher:
Capturing groups are indexed from left to right, starting at one.
Group zero denotes the entire pattern, so the expression m.group(0)
is equivalent to m.group().
So you need to use m.group(1) and m.group(2). And escape the caret ^ in your regex.
import java.util.regex.*;
public class Replace {
public static void main(String[] args) {
String function= "x^2*sqrt(3x)";
Pattern p = Pattern.compile("([a-z0-9]*)\\^([0-9]*)");
Matcher m = p.matcher(function);
String out = function;
if (m.find()) {
System.out.println("GRUPO 0:" + m.group(1));
System.out.println("GRUPO 1:" + m.group(2));
out = m.replaceFirst("pow(" + m.group(1) + ", " + m.group(2) + ')');
}
String funcformat = out;
funcformat = funcformat.replaceAll("sqrt\\(([a-z0-9]*)\\^([0-9]*)]*\\)", "Math.sqrt(pow($1, $2))");
System.out.println("Return Value :"+ function );
System.out.print("Return Value :"+ funcformat );
}
}