Need help in creating a regular expression in Java - java

I am trying to apply regex on a string to obtain the output in the below format.
Input string:
params=Param1{index}~[Value1|Value2|....]^Param2~[Value1|Value2|....]
Output should be in the form of Map<String,List<String>>
Eg.
Key1: Param1
Value : Value1,Value2 upto ValueN
Key2 :Param2
Value: Value1,Value2 uptoValueN
Code:
Her is the code that I am trying to do.
String textPatt = "params";
String key = textPatt.replace("/[\\[]/", "\\[").replace("/[\\]]/", "\\]");
String pattern = new String("[\\?&]" + key + "=([^&#]*)");
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(masterUrl);
List<String> paramList = new ArrayList<String>();
if (m.find()) {
String param = m.group();
if(param != null){
String[] multiParamArr = null;
if(param.indexOf("^") != -1){
multiParamArr = param.split("\\^");
}else{
multiParamArr = new String[1];
multiParamArr[0] = param;
}
if(multiParamArr != null && multiParamArr .length > 0){
Pattern refinePattern = null;
Matcher refineMatcher = null;
String paramKeyy = null;
String paramVal = null;
HashMap<String,List<String>> ParamMap = new HashMap<String,List<String>>();
List<String list = new ArrayList<String>();
for(int i=0;i<multiParamArr.length;i++){
String[] multiParam = null;
String patternKey = "^[^\\~]*";
refinePattern = Pattern.compile(patternKey);
refineMatcher = refinePattern.matcher(multiRefineArr[i]);
if(refineMatcher.find()){
paramKey = refineMatcher.group();
if(paramKey.indexOf("=") !=-1){
patternKey = patternKey.substring(patternKey.indexOf("=")+1);
}
if(paramKey.indexOf("{") !=-1){
patternKey = patternKey.substring(patternKey.indexOf("=")+1,patternKey.indexOf("{"));
}
}
if(multiParamArr[i].indexOf("|") != -1){
multiParam = multiParamArr[i].split("\\|");
int startIndex;
int endIndex;
for(int j=0;j<multiParam.length;j++){
startIndex = 0;
endIndex = 0;
ifmultiParamArr[j].indexOf("[") > -1){
startIndex = multiParamArr[j].indexOf("[")+1;
}
ifmultiParamArr[j].indexOf("]") > -1){
endIndex = multiParamArr[j].indexOf("]");
}else{
endIndex = multiParamArr[j].length();
}
paramVal = multiParamArr[j].substring(startIndex,endIndex);
}
}else{
paramVal = multiParamArr[i].substring(multiParamArr[i].indexOfmultiParamArr[i].indexOf("]"));
}
list.add(paramVal);
}
paramMap.put((paramKey,list);
}
}
}
how to apply a single regex and achieve the output

Instead of trying to create a complex regex and maintain it, you can do it simpler and in a more readable way, in a few steps:
Split on ^
Now you have an array of Strings, each of which contains one of the parameters with its values
Split each string on ~ - you'll get an array of two strings, extract from the first the Param1 (Param2 etc)
From the second you can extract the list of values by splitting on
| (pipe).

Related

Iterating List using DAO Java

In this code I declared a variable that contains the values of the List which is the acode. I can see the values in this List, but I don't know how to iterate over the values using the adao.adao.findAllacctDesc(**acode**). How can i iterate over this list, so that the options show the values?
Here is the code:
<%
TblTaxTypeDAO tdao = DAOFactory.getDaoManager(TblTaxType.class);
TblAccountCodesDAO adao = DAOFactory.getDaoManager(TblAccountCodes.class);
List<TblTaxType> acode = null;
String tcode = request.getParameter("taxt");
String bcode = request.getParameter("bfns");
acode = tdao.findAllAcctCode(bcode, tcode);
Debugger.print(acode);
List<TblAccountCodes> acctdesclist = null;
acctdesclist = adao.findAllacctDesc(acode); <= Having error in this line because acode is a list not a string.
String acctdescoptions = "";
if( acctdesclist!=null) {
if( acctdesclist.size()>0 ) {
for(int i=0; i<acctdesclist.size();i++) {
TblAccountCodes acctcode = (TblAccountCodes) acctdesclist.get(i);
acctdescoptions += "<option value='"+acctcode.getAcctCode()+"'>"+acctcode.getAcctDesc()+"</option>";
acctcode = null;
}
}
}
adao = null;
acctdesclist = null;
%>
<%=acctdescoptions%>
change
List<TblAccountCodes> acctdesclist = null;
acctdesclist = adao.findAllacctDesc(acode); <= Having error in this line because acode is a list not a string.
by
List<TblAccountCodes> acctdesclist = null;
for(TblTaxType T:acode){
acctdesclist.add(adao.findAllacctDesc(T.getString))
}
Is this what you want?
where getString is the function in TblTaxType where you return the string you need.

Words inside square brackes - RegExp

String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = reg.exec(text);
for (int i = 0; i < matchResult.getGroupCount(); i++) {
System.out.println("group" + i + "=" + matchResult.getGroup(i));
}
I am trying to get all blocks which are encapsulated by squared bracets form a path string:
and I only get group0="[build]" what i want is:
1:"[build]" 2:"[something]" 3:"[build]"
EDIT:
just to be clear words inside the brackets are generated with random text
public static String genText()
{
final int LENGTH = (int)(Math.random()*12)+4;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random() * 26) + 97));
}
String str = sb.toString();
str = str.substring(0,1).toUpperCase() + str.substring(1);
return str;
}
EDIT 2:
JDK works fine, GWT RegExp gives this problem
SOLVED:
Answer from Didier L
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String result = "";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = null;
while((matchResult=reg.exec(text)) != null){
if(matchResult.getGroupCount()==1)
System.out.println( matchResult.getGroup(0));
}
I don't know which regex library you are using but using the one from the JDK it would go along the lines of
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
Pattern pat = Pattern.compile(linkPattern);
Matcher mat = pat.matcher(text);
while (mat.find()) {
System.out.println(mat.group());
}
Output:
[build]
[something]
[build]
Try:
String linkPattern = "(\\[[A-Za-z_0-9]+\\])*";
EDIT:
Second try:
String linkPattern = "\\[(\\w+)\\]+"
Third try, see http://rubular.com/r/eyAQ3Vg68N

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);
}

Regex Issue With Multiple Groups

I'm trying to create a regex pattern to match the lines in the following format:
field[bii] = float4:.4f_degree // Galactic Latitude
field[class] = int2 (index) // Browse Object Classification
field[dec] = float8:.4f_degree (key) // Declination
field[name] = char20 (index) // Object Designation
field[dircos1] = float8 // 1st Directional Cosine
I came up with this pattern, which seemed to work, then suddenly seemed NOT to work:
field\[(.*)\] = (float|int|char)([0-9]|[1-9][0-9]).*(:(\.([0-9])))
Here is the code I'm trying to use (edit: provided full method instead of excerpt):
private static Map<String, String> createColumnMap(String filename) {
// create a linked hashmap mapping field names to their column types. Use LHM because I'm picky and
// would prefer to preserve the order
Map<String, String> columnMap = new LinkedHashMap<String, String>();
// define the regex patterns
Pattern columnNamePattern = Pattern.compile(columnNameRegexPattern);
try {
Scanner scanner = new Scanner(new FileInputStream(filename));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.indexOf("field[") != -1) {
// get the field name
Matcher fieldNameMatcher = columnNamePattern.matcher(line);
String fieldName = null;
if (fieldNameMatcher.find()) {
fieldName = fieldNameMatcher.group(1);
}
String columnName = null;
String columnType = null;
String columnPrecision = null;
String columnScale = null;
//Pattern columnTypePattern = Pattern.compile(".*(float|int|char)([0-9]|[1-9][0-9])");
Pattern columnTypePattern = Pattern.compile("field\\[(.*)\\] = (float|int|char).*([0-9]|[1-9][0-9]).*(:(\\.([0-9])))");
Matcher columnTypeMatcher = columnTypePattern.matcher(line);
System.out.println(columnTypeMatcher.lookingAt());
if (columnTypeMatcher.lookingAt()) {
System.out.println(fieldName + ": " + columnTypeMatcher.groupCount());
int count = columnTypeMatcher.groupCount();
if (count > 1) {
columnName = columnTypeMatcher.group(1);
columnType = columnTypeMatcher.group(2);
}
if (count > 2) {
columnScale = columnTypeMatcher.group(3);
}
if (count >= 6) {
columnPrecision = columnTypeMatcher.group(6);
}
}
int precision = Integer.parseInt(columnPrecision);
int scale = Integer.parseInt(columnScale);
if (columnType.equals("int")) {
if (precision <= 4) {
columnMap.put(fieldName, "INTEGER");
} else {
columnMap.put(fieldName, "BIGINT");
}
} else if (columnType.equals("float")) {
if (columnPrecision==null) {
columnMap.put(fieldName,"DECIMAL(8,4)");
} else {
columnMap.put(fieldName,"DECIMAL(" + columnPrecision + "," + columnScale + ")");
}
} else {
columnMap.put(fieldName,"VARCHAR("+columnPrecision+")");
}
}
if (line.indexOf("<DATA>") != -1) {
scanner.close();
break;
}
}
scanner.close();
} catch (FileNotFoundException e) {
}
return columnMap;
}
When I get the groupCount from the Matcher object, it says there are 6 groups. However, they aren't matching the text, so I could definitely use some help... can anyone assist?
It's not entirely clear to me what you're after but I came up with the following pattern and it accepts all of your input examples:
field\\[(.*)\\] = (float|int|char)([1-9][0-9]?)?(:\\.([0-9]))?
using this code:
String columnName = null;
String columnType = null;
String columnPrecision = null;
String columnScale = null;
// Pattern columnTypePattern =
// Pattern.compile(".*(float|int|char)([0-9]|[1-9][0-9])");
// field\[(.*)\] = (float|int|char)([0-9]|[1-9][0-9]).*(:(\.([0-9])))
Pattern columnTypePattern = Pattern
.compile("field\\[(.*)\\] = (float|int|char)([1-9][0-9]?)?(:\\.([0-9]))?");
Matcher columnTypeMatcher = columnTypePattern.matcher(line);
boolean match = columnTypeMatcher.lookingAt();
System.out.println("Match: " + match);
if (match) {
int count = columnTypeMatcher.groupCount();
if (count > 1) {
columnName = columnTypeMatcher.group(1);
columnType = columnTypeMatcher.group(2);
}
if (count > 2) {
columnScale = columnTypeMatcher.group(3);
}
if (count > 4) {
columnPrecision = columnTypeMatcher.group(5);
}
System.out.println("Name=" + columnName + "; Type=" + columnType + "; Scale=" + columnScale + "; Precision=" + columnPrecision);
}
I think the problem with your regex was it needed to make the scale and precision optional.
field\[(.*)\] = (float|int|char)([0-9]|[1-9][0-9]).*(:(\.([0-9])))
The .* is overly broad, and there is a lot of redundancy in ([0-9]|[1-9][0-9]), and I think the parenthetical group that starts with : and preceding .* should be optional.
After removing all the ambiguity, I get
field\[([^\]]*)\] = (float|int|char)(0|[1-9][0-9]+)(?:[^:]*(:(\.([0-9]+))))?

java macroresolver

Hello I am a newbiew to java.
I am trying to write an macroresolver I have string which is represneted as
String s = '{object.attribute}' --> result of the resolver should be 'attribute'
String prefix = '{object.'
String suffix = '}'
that was easy.
i also want to extend to use the same resolver to resolve the following
String s = 'attrName1=$attrValue1$;&attrName2=$attrValue2$;' --> result of the resolver should be attrName1=attrValue1;&attrName2=attrValue2;
String prefix = '$'
String suffix = '$'
i can have a greneralized prefix and suffix passed to the method but not sure what the logic should be.
public class StringMacro {
/**
* #param args
*/
public static void main(String args[]) {
String s = "{article.article_type}";
String prefix = "{article.";
String suffix = "}";
int prefixLength = prefix.length();
int suffixLength = suffix.length();
int startIndex = s.indexOf("{article.");
int prevEndIndex =startIndex+s.indexOf(suffix);
StringBuffer output = new StringBuffer();
while (startIndex != -1 ) {
output.append(s.substring(startIndex+prefixLength,prevEndIndex));
int endIndex = s.indexOf(suffix,startIndex);
if ( endIndex == -1 ) {
output.append(s.substring(startIndex));
break;
}
String macro = s.substring(startIndex+prefixLength,endIndex-1);
prevEndIndex = endIndex+suffixLength;
startIndex = s.indexOf(prefix, prevEndIndex);
}
System.out.println(">>>"+output);
}
}
Help Please!!!!!
this should probably do the trick.
public static void main(String args[]) {
String s = "attr1=$attr1Value$&attr2=$attr2Value$Test"String;
String prefix = "$";
String suffix = "$";
String s1 = "{obj.attr}";
String prefix1 = "{obj";
String suffix1 = "}";
int prefixIndex = 0;
int startIndex = 0;
int endIndex = 0;
Map map = new HashMap();
map.put("attr1Value", "100W");
map.put("attr2Value", "123W");
map.put("attr", "columnist");
StringBuffer buffer = new StringBuffer();
while(prefixIndex != -1){
prefixIndex = s.indexOf(prefix, prefixIndex);
endIndex = s.indexOf(suffix, prefixIndex+prefix.length());
buffer.append(s.substring(startIndex, prefixIndex));
if(endIndex == -1){
break;
}
System.out.println(s.substring(prefixIndex+prefix.length(), endIndex));
buffer.append(map.get(s.substring(prefixIndex+prefix.length(), endIndex)));
prefixIndex = s.indexOf(prefix, endIndex+suffix.length());
startIndex= endIndex+suffix.length();
}
if(prefixIndex == -1){
buffer.append(s.substring(endIndex+suffix.length()));
}
System.out.println(buffer);
}
}

Categories

Resources