Regular Expression to detect query in java - java

I am trying to search a String using Regular Expression.
For example: this is my sample String
**if (c == 0) {
count = 0;
du.insert(ipAddress, c);
} else {
count = c;
}
getDate();
String query1 = "select * from loginmaster where username = '" + username + "' and password = '" + password + "' ;";
//out.println(query1);
//out.println(request.getParameter("Group1"));
session.setAttribute("group", request.getParameter("Group1"));
if (count < 3) {
if (request.getParameter("Group1").equals("With")) {
LoginQuery q = new LoginQuery();
checked = q.Checker(query1);
if (checked == false) {
connection.getConnection();
connection.getDML("insert into attack values('"+ipAddress+"','"+date+"','Attack Detected')");
}
}**
and i am trying to find querys in this String using Regular Expression
String regExp = "\b(ALTER|CREATE|DELETE|DROP|EXEC(UTE){0,1}|INSERT( +INTO){0,1}|MERGE|SELECT|UPDATE|UNION( +ALL){0,1})\b";
and
String regExp = "(;|\\s)(exec|execute|select|insert|update|delete|create|alter|drop|rename|truncate|backup|restore)\\s";
But i am not getting any Output nor Error.
Remaining Code is:
Pattern p = Pattern.compile(regExp, Pattern.CASE_INSENSITIVE);
while ((line = reader.readLine()) != null) {
Matcher m = p.matcher(line);
if (m.matches()) {
JOptionPane.showMessageDialog(this, "innnnnnnnnnn");
System.err.println(m.group(1));
}
}
Pls help

Your regexes will not match with the input string, because of case mismatch.
Your regular expressions written in upper-case but your input string contains lower-case matches. So, either make the regexes case-insensitive or convert it to lower-case.
By the way, your regexes couldn't separate query insert into attack ... and method: du.insert(ipAddress, c);

Related

SQL query for user t1, t2, . . . , tm terms in where clause

User gives String as input of terms they can be t1, ...tm now I have to embed these t1,... tm in sql where clause.
Select * from documents where term = t1 OR term = t2 ...... term=tm
At the moment I am splitting string into string array:
String[] terms = term.split("\\s+");
for (int i =0; i<term.length; i++) {
if (i == term.length -1) {
str += "term = " + term[i];
}
else {
str += "term = " + term[i] + " OR ";
}
Now I am getting
string str= "term = document OR term = word Or term = explanation".
But term is my column name and document value how can I pass this in where clause of SQL?
I assume, since you are splitting by spaces, that the user's input is like this:
document word explanation
First use trim() to remove any leading spaces from term.
Then inside the for loop enclose all the items of the array in single quotes (although this is not the safe way to construct a query, you could use a Prepared Statement and ? placeholders):
String[] terms = term.trim().split("\\s+");
for (int i = 0; i < terms.length; i++) {
str += "term = '" + terms[i] + "'";
if (i < terms.length -1) {
str += " OR ";
}
}
The result will be:
term = 'document' OR term = 'word' OR term = 'explanation'

Separate into column without using split function

I am trying to separate these value into ID, FullName and Phone. I know we can split it by using java split function. But is there any other ways to separate it? Values:
1 Peater John 2522523254
10 Neal Tom 2522523254
11 Tom Jackson 2522523254
111 Jack Smith 2522523254
12 Brownson Black 2522523254
I tried to use substring method but it won't work properly.
String id = line.substring(0, 3);
If I do this then it will work till 4th line, but other won't work properly.
If it is fixed length you can use String.substring(). But you should also trim() the result before you try to convert it to numeric:
String idTxt=line.substring(0,4);
Long id=Long.parseLong(idTxt.trim());
String name=line.substring(5,25).trim(); // or whatever the size is of name column.
You can use regex and Pattern
Pattern pattern = Pattern.compile("(\\d*)\s*([\\w\\s]*)\\s*(\\d*)");
Matcher matcher = pattern.matcher(content);
if (matcher.find()) {
string id = matcher.group(0);
string name = matcher.group(1);
string phone = matcher.group(2);
}
package Generic;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Main
{
public static void main(String[] args)
{
String txt=" 12 Brownson Black 2522523254";
String re1=".*?"; // Non-greedy match on filler
String re2="(\\d+)"; // Integer Number 1
String re3="(\\s+)"; // White Space 1
String re4="((?:[a-z][a-z]+))"; // Word 1
String re5="(\\s+)"; // White Space 2
String re6="((?:[a-z][a-z]+))"; // Word 2
String re7="(\\s+)"; // White Space 3
String re8="(\\d+)"; // Integer Number 2
Pattern p = Pattern.compile(re1+re2+re3+re4+re5+re6+re7+re8,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher m = p.matcher(txt);
if (m.find())
{
int id = Integer.parseInt(m.group(1));
String name =m.group(3) + " ";
name = name+m.group(5);
long phone = Long.parseLong(m.group(7));
System.out.println(id);
System.out.println(name);
System.out.println(phone);
}
}
}
What about this:
int first_space;
int last_space;
first_space = my_string.indexOf(' ');
last_space = my_string.lastIndexOf(' ');
if ((first_space > 0) && (last_space > first_space))
{
long id;
String full_name;
String phone;
id = Long.parseLong(my_string.substring(0, first_space));
full_name = my_string.substring(first_space + 1, last_space);
phone = my_string.substring(last_space + 1);
}
Use a regexp:
private static final Pattern RE = Pattern.compile(
"^\\s*(\\d+)\\s+(\\S+(?: \\S+)*)\\s+(\\d+)\\s*$");
Matcher matcher = RE.matcher(s);
if (matcher.matches()) {
System.out.println("ID: " + matcher.group(1));
System.out.println("FullName: " + matcher.group(2));
System.out.println("Phone: " + matcher.group(3));
}
You can use a StringTokenizer for this. You won't have to worry about amount of spaces and/or tabs before or after your values, and no need for complex regex expressions:
String line = " 1 Peater John\t2522523254 ";
StringTokenizer st = new StringTokenizer(line, " \t");
String id = "";
String name = "";
String phone = "";
// The first token is your id, you can parse it to an int if you like or need it
if(st.hasMoreTokens()) {
id = st.nextToken();
}
// Loop over the remaining tokens
while(st.hasMoreTokens()) {
String token = st.nextToken();
// As long a there are other tokens, you're processing the name
if(st.hasMoreTokens()) {
if(name.length() > 0) {
name = name + " ";
}
name = name + token;
}
// If there are no more tokens, you've reached the phone number
else {
phone = token;
}
}
System.out.println(id);
System.out.println(name);
System.out.println(phone);

Regex for JAVA to get optional group

I try to match non english text from 用量 to name=用量 and 用量2 to name=用量 and number=2. I tried (\p{L}+)(\d*) on RegexPlanet, it works, but when get it run in java, can not get the 2 out the second test case.
Here's the code:
String pt = "(?<name>\\p{L}+)(?<number>\\d*)";
Matcher m = Pattern.compile(pt).matcher(t.trim());
m.find();
System.out.println("Using [" + pt + "] vs [" + t + "] GC=>" +
m.groupCount());
NameID n = new NameID();
n.name = m.group(1);
if (m.groupCount() > 2) {
try {
String ind = m.group(2);
n.id = Integer.parseInt(ind);
} catch (Exception e) { }
}
String t = "用量2";
String pt = "^(?<name>\\p{L}+)(?<number>\\d*)$";
Matcher m = Pattern.compile(pt).matcher(t.trim());
if (m.matches()) {
String name = m.group("name");
Integer id = m.group("number").length() > 0 ? Integer.parseInt(m.group("number")) : null;
System.out.println("name=" + name + ", id=" + id); // name=用量, id=2
}
Your regex works fine, but your Java code has some issues. See javadoc for groupCount():
Group zero denotes the entire pattern by convention. It is not included in this count.

How to match the text file against multiple regex patterns and count the number of occurences of these patterns?

I want to find and count all the occurrences of the words unit, device, method, module in every line of the text file separately. That's what I've done, but I don't know how to use multiple patterns and how to count the occurrence of every word in the line separately? Now it counts only occurrences of all words together for every line. Thank you in advance!
private void countPaterns() throws IOException {
Pattern nom = Pattern.compile("unit|device|method|module|material|process|system");
String str = null;
BufferedReader r = new BufferedReader(new FileReader("D:/test/test1.txt"));
while ((str = r.readLine()) != null) {
Matcher matcher = nom.matcher(str);
int countnomen = 0;
while (matcher.find()) {
countnomen++;
}
//intList.add(countnomen);
System.out.println(countnomen + " davon ist das Wort System");
}
r.close();
//return intList;
}
Better to use a word boundary and use a map to keep counts of each matched keyword.
Pattern nom = Pattern.compile("\\b(unit|device|method|module|material|process|system)\\b");
String str = null;
BufferedReader r = new BufferedReader(new FileReader("D:/test/test1.txt"));
Map<String, Integer> counts = new HashMap<>();
while ((str = r.readLine()) != null) {
Matcher matcher = nom.matcher(str);
while (matcher.find()) {
String key = matcher.group(1);
int c = 0;
if (counts.containsKey(key))
c = counts.get(key);
counts.put(key, c+1)
}
}
r.close();
System.out.println(counts);
Here's a Java 9 (and above) solution:
public static void main(String[] args) {
List<String> expressions = List.of("(good)", "(bad)");
String phrase = " good bad bad good good bad bad bad";
for (String regex : expressions) {
Pattern gPattern = Pattern.compile(regex);
Matcher matcher = gPattern.matcher(phrase);
long count = matcher.results().count();
System.out.println("Pattern \"" + regex + "\" appears " + count + (count == 1 ? " time" : " times"));
}
}
Outputs
Pattern "(good)" appears 3 times
Pattern "(bad)" appears 5 times

Java special characters RegEx

I want to achieve following using Regular expression in Java
String[] paramsToReplace = {"email", "address", "phone"};
//input URL string
String ip = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
//output URL string
String op = "http://www.google.com?name=bob&email=&address=&phone=";
The URL can contain special characters like %
Try this expression: (email=)[^&]+ (replace email with your array elements) and replace with the group: input.replaceAll("("+ paramsToReplace[i] + "=)[^&]+", "$1");
String input = "http://www.google.com?name=bob&email=okATtk.com&address=NYC&phone=007";
String output = input;
for( String param : paramsToReplace ) {
output = output.replaceAll("("+ param + "=)[^&]+", "$1");
}
For the example above. you can use split
String[] temp = ip.split("?name=")[1].split("&")[0];
op = temp[0] + "?name=" + temp[1].split("&")[0] +"&email=&address=&phone=";
Something like this?
private final static String REPLACE_REGEX = "=.+\\&";
ip=ip+"&";
for(String param : paramsToReplace) {
ip = ip.replaceAll(param+REPLACE_REGEX, Matcher.quoteReplacement(param+"=&"));
}
P.S. This is only a concept, i didn't compile this code.
You don't need regular expressions to achieve that:
String op = ip;
for (String param : paramsToReplace) {
int start = op.indexOf("?" + param);
if (start < 0)
start = op.indexOf("&" + param);
if (start < 0)
continue;
int end = op.indexOf("&", start + 1);
if (end < 0)
end = op.length();
op = op.substring(0, start + param.length() + 2) + op.substring(end);
}

Categories

Resources