java regular expression between characters java - java

My Java code:
String subjectString = "BYWW4 AterMux TP 46[_221] \n"
+ "FHTTY TC AterMux TP 9 \n"
+ "TUI_OO AterMux TP 2[_225] \n"
+ "F-UYRE TC AterMux TP 2 \n"
+ "RRRDSA AterMux TP 31[_256] ";
String textStr[] = subjectString.split("\n");
for (int i = 0; i < textStr.length; i++) {
String ResultString = null;
try {
Pattern regex = Pattern.compile("????????");
Matcher regexMatcher = regex.matcher(textStr[i]);
if (regexMatcher.find()) {
ResultString = regexMatcher.group();
System.out.println(ResultString); ///
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
}
I want the program to print the value after word (TP) and before ([) on this code to get result like below:4692231

You can use regexp TP\s*(\d+)\[ (double backslashes in Java code) and get a value with regexMatcher.group(1).
But you should not recreate it on each iteration of the loop, you should use Pattern.compile once per regexp.

Related

Java: Get all Strings using Regex

I'm trying to get all the strings from a javascript script, I created a code, but it's not catching all, it's skipping some
My Code
String Strings;
public String GetStrings(String str){
try{
String Str= str;
Strings = "";
while(true){
Pattern pattern = Pattern.compile("('|\")");
Matcher matcher = pattern.matcher(Str);
if(matcher.find()){
Pattern pattern1 = Pattern.compile("(" + matcher.group(1) + "[^" + matcher.group(1) + "]*" + matcher.group(1) + ")");
Matcher matcher1 = pattern1.matcher(Str);
if(matcher1.find()){
Strings += "|" + matcher1.group(1) + "|";
Str = Str.replace(matcher1.group(1)," ");
}
}else{
break;
}
}
}catch(Exception err){return err.toString(); }
return Strings;
}
Input
var A="&";var B="(";var D="[]";var X="'";var W='&';var Q='';var STR="'";var Q="'******'";var G="^";var F="...";var T='$';var wm = "()"
console.log(A + B + D + "^" + wm + '#');
Output
|"&"||"("||"[]"||"'"||'&'||''||"'******'"||"^"||"..."||'$'||"()"||'#'|
As you can see not captured all the strings, some did not appear, if anyone has any solution or can point the problem, please help me
You need to use following regex:
(\"(.*?)\")|(\'(.*?)\')
example:
public String getStrings(String str){
String regex = "(\\\"(.*?)\\\")|(\\'(.*?)\\')";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
String output = "";
while (matcher.find()){
output = output+"|"+matcher.group(0)+"|";
}
return output;
}
Output:
|"&"||"("||"[]"||"'"||'&'||''||"'"||"'******'"||"^"||"..."||'$'||"()"||"^"||'#'|
Regex Explanation
Input and expected output is not matching but according what i understood is
public String GetStrings(String str){
StringBuffer b = new StringBuffer();
for (int i = 0; i < str.length(); ++i) {
char ch = str.charAt(i);
if (Character.isWhitespace(ch))
b.append("\\s");
else if (Character.isDigit(ch))
b.append("\\d");
else if (Character.isUpperCase(ch))
b.append("A-Z");
else if (Character.isLowerCase(ch))
b.append("a-z");
}
b.append("||");
}

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 get the string after a word

I would like to get the sub-string after the term "[ DevStatusReq ] =" in the following content
"10-01-2018 10:24:08.006 : |=> [ DevStatusReq ] = 0x06".I want to use regex.
Here is my code :
String margin = LogExtract.extractDataInFile(path, "Margin", "Margin = (.*?) dB");
String devStatusReq = LogExtract.extractDataInFile(path, "DevStatusReq", "[ DevStatusReq ] = (.*) ");
System.out.println("Margin : " + margin + " | DevStatusReq : " + devStatusReq );
My method which return the result found is here :
public static String extractDataInFile(String filePath,String element, String filter) {
String result = element + "has not been found ";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if(line.contains(element)) {
element = line;
Pattern pattern = Pattern.compile(filter);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
result= matcher.group(1);
}
}
}
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
The console displays :
Margin : 39 | DevStatusReq : DevStatusReqhas not been found
My regex in the second call of the method is wrong. Can you help me please ?
Thank you!
In regular expressions [] are special characters to build a set of values :
so [ DevStatusReq ] means one of the following letter DSR evtausq
The right pattern for you is \[ DevStatusReq \] = (.*)
In Java \ is a special character, so you need to escape it and your pattern in the code will be :
LogExtract.extractDataInFile(path, "DevStatusReq", "\\[ DevStatusReq \\] = (.*) ");

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.

Regular Expression to detect query in 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);

Categories

Resources