I am using the below regex expression :
Pattern p = Pattern.compile("(.*?)(\\d+)?(\\..*)?");
while(new File(fileName).exists())
{
Matcher m = p.matcher(fileName);
if(m.matches()) { //group 1 is the prefix, group 2 is the number, group 3 is the suffix
fileName = m.group(1) + (m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1)) + (m.group(3)==null ? "" : m.group(3));
}
}
This works fine for filename like abc.txt but if there is any file with name abc1.txt the above method is giving abc2.txt. How to make the regex condition or change (m.group(2) == null ? "_copy" + 1 : (Integer.parseInt(m.group(2)) + 1)) so that it returns me abc1_copy1.txt as new filename and not abc2.txt and so forth like abc1_copy2 etc.
Pattern p = Pattern.compile("(.*?)(_copy(\\d+))?(\\..*)?");
while(new File(fileName).exists())
{
Matcher m = p.matcher(fileName);
if (m.matches()) {
String prefix = m.group(1);
String numberMatch = m.group(3);
String suffix = m.group(4);
int copyNumber = numberMatch == null ? 1 : Integer.parseInt(numberMatch) + 1;
fileName = prefix;
fileName += "_copy" + copyNumber;
fileName += (suffix == null ? "" : suffix);
}
}
I'm not a java guy, but in general, you should use libarary functions/classes for parsing filenames as many platforms have different rules for them.
Look at:
http://people.apache.org/~jochen/commons-io/site/apidocs/org/apache/commons/io/FilenameUtils.html#getBaseName(java.lang.String)
Related
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("||");
}
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.
I have a String template like this:
"Thanks, this is your value : [value]. And this is your account number : [accountNumber]"
And i have inputs like this:
input 1 : "Thanks, this is your value : 100. And this is your account number : 219AD098"
input 2 : "Thanks, this is your value : 150. And this is your account number : 90582374"
input 3 : "Thanks, this is your value : 200. And this is your account number : 18A47"
I want output like this:
output 1 : "[value] = 100 | [accountNumber] = 219AD098"
output 2 : "[value] = 150 | [accountNumber] = 90582374"
output 3 : "[value] = 200 | [accountNumber] = 18A47"
How to do that? Maybe using Regex?
note : the template is not fixed.. the only thing that fixed is [value] and [accountNumber]..
use this regex
(?<=value : )(\d+)|(?<=number : )(.+)(?=")
this will extract both the values from the lines that you want. after getting them you can concatenate them with anything you want like your output string.
the code to use this regex will be like this
Pattern pattern = Pattern.compile("(?<=value : )(\d+)|(?<=number : )(.+)(?=\")");
Matcher matcher = pattern.matcher(SOURCE_TEXT_LINE);
List<String> allMatches = new ArrayList<String>();
while (matcher.find()) {
allMatches.add(matcher.group());
}
so this way you will get the matched values in this array list, of you can use a simple array if you prefer.
String text = "Thanks, this is your value : 100. And this is your account number : 219AD098";
Pattern pattern = Pattern
.compile("Thanks, this is your value : (\\d+). And this is your account number : (\\w+)");
Matcher matcher = pattern.matcher(text);
matcher.find();
String outputText = "[value] = " + matcher.group(1)
+ " | [accountNumber] = " + matcher.group(2);
System.out.println(outputText);
is is easy to do without regex too:
String input = getInput();
String[] inputLines = input.split("\n");
String output = "";
int counter = 1;
for(string line : inputLines)
{
int subValStart = line.indexOf("value : ");
string val = line.substring(subValStart, line.indexOf("|") - subValStart);
string accNum = line.substring("account number : ");
output += "output " + counter + " :\"[value] = "+ val + " | [accountNumber] = " + accNum + "\"\n";
counter++;
}
Try this, StringUtils.subStringBefore
String sCurrentLine = CURRENT_LINE;
String[] splitedValue = sCurrentLine.split(":");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(splitedValue[0].replace("input", "output"));
stringBuilder.append(": \"[value] = "+StringUtils.substringBefore(splitedValue[2], "."));
stringBuilder.append(" | [accountNumber] = "+splitedValue[3]);
You can use regular expression.
Here is full example
package snippet;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) throws CoffeeDOMException, IOException {
String test = "Thanks, this is your value : 100 . And this is your account number : 219AD098";
String valueExpression = "\\svalue\\s:([^.]+)";
String accExpresion = "\\saccount\\snumber\\s:([^$]+)";
System.out.println("Value:" + runSubRegex(valueExpression, test));
System.out.println("Account:" + runSubRegex(accExpresion, test));
}
private static String runSubRegex(String regex, String tag) {
Pattern p = Pattern.compile(regex);
Matcher matcher = p.matcher(tag);
if (matcher.find()) {
return matcher.group(1);
}
return null;
}
}
Output
Value: 100
Account : 219AD098
Just check it out.
String template = "Thanks, this is your value : -XXXX-. And this is your account number : -XXXX- -XXXX- Value,Account Number";
String input = "Thanks, this is your value : 100. And this is your account number : 219AD098";
/*String template = "You can use -XXXX- mehod to read values from -XXXX- Value 1,value 2";
String input = "You can use this mehod to read values from custom string template";*/
String[] splitValue = template.split("-XXXX-");
for (String splitValueTemp : splitValue) {
input = input.replace(splitValueTemp, "!");
}
List<String> value = Arrays.asList(input.split("!"));
List<String> Key = Arrays.asList(splitValue[splitValue.length - 1].split(","));
if (value != null && value.size() > 1) {
int iCnt = 0;
for (String opValue : value.subList(1, value.size())) {
if (Key.size() > iCnt) {
System.out.println(Key.get(iCnt).trim() + " : " + opValue.trim());
}
iCnt++;
}
}
O/P:
Value : 100
Account Number : 219AD098
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);
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);
}