Java regex - eval for replacement
Hi
Could you please help me in a regex problem?
I have a regex pattern in a string. I want to apply this on a text, and wherever it is applied the matched text should be replaced by the length of the found text. Now I have done it with a while loop, but it takes too long to process:
Pattern p = Pattern.compile(patternString);
Matcher m = p.matcher(text);
// I dont know how to get this job done with m.replaceAll(). Thats why the following loop
// By the way, in Perl there is "eval" with which we can do this
while (m.find()) {
String foundText = m.group();
Pattern p2 = Pattern.compile( Pattern.quote(foundText) );
text = p2.matcher(text).replaceAll( foundText.length() );
}Is there a better way? Kindly help.
Thanks
Sri
There's nothing like Perl's /e modifier (or Ruby's gsub) in Java's regex support, but ther's a much better alternative to what you're doing. In addition to replaceAll() and replaceFirst(), Matcher provides the lower-level methods appendReplacement() and appendTail() that offer you more control over the replacement process. Check this out: Pattern p = Pattern.compile(patternString);
Matcher m = p.matcher(text);
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, String.valueOf(m.group().length()));
m.appendTail(sb);
text = sb.toString(); Or you could just use Elliott Hughes' Rewriter class. (You may need to get rid of some code in the main() method that references other utility classes of his; Rewriter itself only depends the java.util.regex package.)
Similar Messages
-
What is the escape character for DOT in java regex?
How to specify a dot character in a java regex?
. itself represents any character
\. is an illegal escape characterThe regex engine needs to see \. but if you're putting it into a String literal in a .java file, you need to make it \\., as Rene said. This is because the compiler also uses \ as an escape character, so it will take the first \ as escaping the second one, and remove it, and the string that gets passed onto the regex will be \.
-
Java Regex, how do I replace \\ with \\\\?
Hello,
The following line doesn't work: someString.replaceAll("\\", "\\\\");
The error I get is the following:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
^
at java.util.regex.Pattern.error(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.util.regex.Pattern.<init>(Unknown Source)
at java.util.regex.Pattern.compile(Unknown Source)
at java.lang.String.replaceAll(Unknown Source)
at TSPEngine.main(TSPEngine.java:34)
How do I fix this?
Thanks in advance,Interference wrote:
Hello,
The following line doesn't work: someString.replaceAll("\\", "\\\\");
The error I get is the following:
Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1"\\" is how you represent "\" in a String literal in Java, since "\" is an escape character. But "\" is also an escape character in regular expressions, meaning to represent a literal "\" in a Java regex you need "\\\\". Your second string should be fine since it's not interpreted as a regular expression to my knowledge.
Edit:
No, the second string DOES need to be "\\\\\\\\".
Edited by: endasil on 17-May-2010 11:46 AM -
Converting sed regex to Java regex
I am new to reguler expressions.I have to write a regex which will do some replacements
If the input string is something like test:[email protected];value=abcd
when I apply the regex on it,this string should be changed to test:[email protected];value=replacedABC
I am trying to replace test.com and abcd with the values i have supplied...
The regex I have come up with is in sed
s/\(^.*@\)\(.*\)$/\1replaceTest.com;value=replacedABC/i
Now I am trying to get the regex in Java,I would think it will be something like (^.*@\)(.*\)$\1replaceTest.com;value=replacedABC
But not sure How i can test this.Any idea on how to make sure my java regex is valid and does the required replacements?rsv-us wrote:
Yep.Agreed.
Since that these replacements should be done in a single regex.Note that the sed replacement I posted is really made of two replacements! Just like your Java solution would.
I think once we send this regex to the third party,they will haev to use either sed or perl(will perl do this replacements,not sure though) to get the output.
Since we are not sure what tool/software the third party is going to use,I was trying to see how i can really test this.Then I read about sed and this regex as is didn't work,so,I had to put all the sed required / and then the regex had become like s/\(^.*@\)\(.*\)$"/1replaceTest.com;value=replacedabcd/iAgain: AFAIK that does not work. I tried it like this:
{code}$ echo test:[email protected];value=abcd | sed 's/\(^.*@\)\(.*\)$"/1replaceTest.com;value=replacedabcd/i'and the following is returned:test:[email protected] that we will have to send the java regex to the third party,I was trying to see how i can convert this sed regex to java.If I am right,with jave regex,we won;t be able to all the finds and replacements in a single regex..right?...If this is true,this will leave me a question of whether I need to send the sed regex to the thrid party or If I send java regex,they have to convert that to either sed or perl regex.
One more question,can we do thse replacement in perrl also,if so,what will the equivalent regex for this in perl?
I can't understand what you are talking about. The large amount of spelling errors also doesn't help to make it clearer.
Good luck though. -
Script for replacing Image from a frame into InDesign document file
Hi All,
I am having an indesign document (indd) file with images and texts. I am using InDesign Server CS4 to run the scripts via SOAP.
My requirement is to replace any of the images from the required frame/s of indesign document through scripting (I already have frame id of which image needs to be replaced). I have written written java-script file (as given below): but when I execute this java-script on InDesign Server via SOAP, I get follwoing error into InDesign Server:
10/03/09 15:15:54 INFO [javascript] Executing File: \\Server_IP_Address\JavaScript_File_Path\JavaScript_File.js
10/03/09 15:16:01 ERROR [link manager] Link missing.; file:C:/help.gif
10/03/09 15:16:01 ERROR [link manager] Link missing.; file:C:/Documents%20and%20Settings/All%20Users/Documents/My%20Pictures/Sample%20Pictures/ Water%20lilies.jpg
10/03/09 15:16:01 ERROR [link manager] Link missing.; file:C:/Documents%20and%20Settings/All%20Users/Documents/My%20Pictures/Sample%20Pictures/ Winter.jpg
Following is the java-script that is being used for replacing image from indd's frame:
var myDocument = app.open(File('//Server_IP_Address/InDesignDocument_File_Path/Sample.indd'));
var tmp_frmid="1339"; //frame id of which image needs to be replaced.
for (var i=0;i<myDocument.pages.length;i++)
var objPage=myDocument.pages.item(i);
var objPageitems = objPage.pageItems;
try
var obj = objPageitems.itemByID(tmp_frmid);
obj.images[0].remove;
obj.appliedObjectStyle = null;
var myImage=obj.place(File('//Server_IP_Address/Images_to_be_reolaced_Path/ImageFile.jpg'));
var old_height = myImage.geometricBounds[2] - myImage.geometricBounds[0];
var new_height = obj.geometricBounds[2] - obj.geometricBounds[0];
var old_width = myImage.geometricBounds[3] - myImage.geometricBounds[1];
var new_width = obj.geometricBounds[1] + ((new_height / old_height) * old_width);
myImage.geometricBounds = [obj.geometricBounds[0] + "mm", obj.geometricBounds[1] + "mm", obj.geometricBounds[2] + "mm", new_width + "mm"];
var diff = obj.geometricBounds[1] - myImage.geometricBounds[1];
myImage.move( undefined, [diff,0] );
break;
catch(e)
myDocument.save('//Server_IP_Address/InDesignDocument_File_Path/Sample.indd');
var previewFile = File('//Server_IP_Address/Images_to_be_reolaced_Path/ImageFile.jpg');
app.jpegExportPreferences.jpegQuality["JPEGOptionsQuality.low"];
app.documents.item(0).exportFile(ExportFormat.jpg, previewFile);
myDocument.close();
I have very urgent requirement; if anyone have any idea; please suggest me. \
It would be highly appreciable.
Kind Regards,
Prashant.http://www.automatication.com/selection-to-pdf-script.html
Harbs
http://www.in-tools.com -
Java Regex groups with quantifiers.
I'm a bit stuck on a regex , i want to do something similar to this :
(dog){6}
dogdogdogdogdogdog
and returned I want 6 seperate groups with 'dog' in each one.
This works fine with jakarta-regexp but when I use the {} quantifiers in Java regex I lose the groupings which i'm looking for and just get a single group with a value of 'dog'
I'm sure i'm doing something something stupid here and help would be great!You can't do this with the SunJDK regex engine without using find() with a Matcher.
I consider this feature of jakarta-regex to be a bug and reported it (and a couple of other features) as such several years ago. The feature makes it incompatible with most regex engines I have used. -
Hello - I am trying to find a list of all illegal characters which have to be escaped in JAVA Regex pattern matching but I cannot find a complete list.
Also I understand that when doing the replaceall function that there is a special list of characters which can't be used for that as well, which also have to be escaped differently.
If anyone has access to a full complete list as to when to escape and how I would greatly appreciated it!
Thanks,
DanI also noticed this below link:
http://java.sun.com/docs/books/tutorial/extra/regex/literals.html
It said the following characters are meta-characters in regex API:
( [ { \ ^ $ | ) ? * + .
But it also says the below:
Note: In certain situations the special characters listed above will not be treated as metacharacters. You'll encounter this as you learn more about how regular expressions are constructed. You can, however, use this list to check whether or not a specific character will ever be considered a metacharacter. For example, the characters ! @ and # never carry a special meaning.
Does anyone know if there would be any issues if I escaped when a character didn't need to be escaped? -
Hello,
I have parsed a text file and want to use a java regex pattern to get the status like "warning" and "ok" ("ok" should follow the "warning" then need to parser it ), does anyone have idea? How to find ok that follows the warning status? thanks in advance!
text example
121; test test; test0; ok; test test
121; test test; test0; ok; test test
123; test test; test1; warning; test test
124; test test; test1; ok; test test
125; test test; test2; warning; test test
126; test test; test3; warning; test test
127; test test; test4; warning; test test
128; test test; test2; ok; test test
129; test test; test3; ok; test testjava code:
String flag= "warning";
while ((line= bs.readLine()) != null) {
String[] tokens = line.split(";");
for(int i=1; i<tokens.length; i++){
Pattern pattern = Pattern.compile(flag);
Matcher matcher = pattern.matcher(tokens);
if(matcher.matches()){
// save into a listsorry, I try to expain it in more details. I want to parse this text file and save the status like "warning" and "ok" into a list. The question is I only need the "ok" that follow the "warning", that means if "test1 warning" then looking for "test1 ok".
121; content; test0; ok; 12444 <-- that i don't want to have
123; content; test1; warning; 126767
124; content; test1; ok; 1265 <-- that i need to have
121; content; test9; ok; 12444 <-- that i don't want to have
125; content; test2; warning; 2376
126; content; test3; warning; 78787
128; content; test2; ok; 877666 <-- that i need to have
129; content; test3; ok; 877666 <-- that i need to have
// here maybe a regex pattern could be deal with my problem
// if "warning|ok" then list all element with the status "warning and ok"
String flag= "warning";
while ((line= bs.readLine()) != null) {
String[] tokens = line.split(";");
for(int i=1; i<tokens.length; i++){
Pattern pattern = Pattern.compile(flag);
Matcher matcher = pattern.matcher(tokens);
if(matcher.matches()){
// save into a list -
Java Regex Pipe Delimited ?
Hello
I am trying to split the string which is pipe delimited. I am new to Regex and new to Java.
My Java/Regex code line to split is:
listColumns = aLine.split("\\|"); // my code has 2 backslash-escapes chars plus 1 pipe char but this forum does not allow me to put pipes or escapes correctly and plain text help is of NO HELP 8^(
My input string has 3 leading and 4 trailing pipe characters
My Output from split: (3 leading emptry strings work but 4 trailing pipe delimiters dont work)
SplitStrings2:[]
SplitStrings2:[]
SplitStrings2:[]
SplitStrings2:[col1]
SplitStrings2:[col3]
SplitStrings2:[col4]
I do get 3 empty strings for all 3 leading pipes but no empty strings for the any traling 4 pipe characters.
What do I need to change the code such that all repeated pipes resulted in same number of empty strings returned by split method?
thanks
YuriB
Edited by: yurib on Nov 28, 2012 12:25 PM
Edited by: yurib on Nov 28, 2012 12:25 PM
Edited by: yurib on Nov 28, 2012 12:29 PM1. The pipe is a meta-character so escape it.
2. Split rolls things up for you unless you tell it otherwise.
String s = "|||A|B|C||||";
String[] array = s.split("[|]", 10);
for(int i=0; i < array.length; i++)
System.out.println("" + i + ": " + array); -
Hi:
I have the following texts in a flat file:
scheduler is running
system default destination: llp
device for ps3: /dev/ps3
device for ps: /dev/ecpp0
device for llp: /dev/ecpp0
How can I use java regex to print out the string after "device for " in this case the string "ps3" ,"ps" and "llp".static final Pattern DEVICE_PATTERN = Pattern.compile(
"device for ([^:]++)" );
String text = "";
Matcher m = DEVICE_PATTERN.matcher( text );
while ( (text = bufferedReader.readLine()) != null ) {
if ( m.reset(text).lookingAt() ) {
String device = m.group( 1 );
} -
Hi,
what is the connection between sed regex rules and java regex rule. Is there an easy way to convert sed to java? or do i have to learn sed?....
ThanksIIRC, Java regex rules are like Perl's (although the syntax for invocation differs a bit), and Perl's are basically a superset of sed's, except there's a difference with parentheses. In Perl/Java, parentheses always group and you have to backslash-quote them to make them interpreted as plain parenthesis characters, whereas in sed, you backslash-quote them to make them be interpreted as grouping indicators.
Why? What problem are you having? -
How do you get java regex to match two different pattern
Hi,
I am having trouble getting getting java regex to match two pattern: "unknown host" or "100%".
Here is a snippet of my code:
try{
Process child = Runtime.getRuntime().exec(" perl c:\\ping.pl");
BufferedReader in = new BufferedReader( new InputStreamReader( child.getInputStream() ));
String patternStr = "(unknown host | 100 %)";
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(" ");
String line = null;
while ( (line = in.readLine()) != null){
System.out.println(line);
matcher.reset(line);
if (matcher.find())
// line matches throws pattern
System.out.println("match string");
else
System.out.println("no matches");
I thought the "|" means OR but somehow it is not working.
kirk123Hi,
with String patternStr = "(unknown host | 100 %)"; you are looking
for the strings "unknown host " OR " 100 %", with the spaces after host and before 100.
Try "(unknown host|100 %)"
hope, this will help you -
Java.lang.NumberFormatException: For input string: "DESCRIPTION="
Colleagues,
eBis 11.5.10.2.
I'm getting a Warning in the concurrent manager when I submit a programme that has an attached xml template. The warning is stating: -
------------- 1) PUBLISH -------------
Beginning post-processing of request 2667735 on node BAMBI at 02-SEP-2011 17:32:56.
Post-processing of request 2667735 failed at 02-SEP-2011 17:32:57 with the error message:
One or more post-processing actions failed. Consult the OPP service log for details.
------------- 2) PRINT -------------
Not printing the output of this request because post-processing failed.
When I consult the OPP log in Sysadmin, I can see a not very helpful message: -
[9/2/11 5:32:57 PM] [UNEXPECTED] [36822:RT2667735] java.lang.NumberFormatException: For input string: "DESCRIPTION="
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:447)
at java.lang.Integer.parseInt(Integer.java:497)
at oracle.apps.xdo.generator.pdf.PDFGenerator.setFont(PDFGenerator.java:629)
at oracle.apps.xdo.generator.pdf.PDFGenerator.setProperties(PDFGenerator.java:468)
at oracle.apps.xdo.generator.ProxyGenerator.setProperties(ProxyGenerator.java:1373)
at oracle.apps.xdo.template.fo.FOHandler.startElement(FOHandler.java:262)
at oracle.apps.xdo.template.fo.FOHandler.startElement(FOHandler.java:204)
at oracle.apps.xdo.common.xml.XSLTMerger.startElement(XSLTMerger.java:55)
at oracle.xml.parser.v2.XMLContentHandler.startElement(XMLContentHandler.java:167)
at oracle.xml.parser.v2.NonValidatingParser.parseElement(NonValidatingParser.java:1182)
at oracle.xml.parser.v2.NonValidatingParser.parseRootElement(NonValidatingParser.java:301)
at oracle.xml.parser.v2.NonValidatingParser.parseDocument(NonValidatingParser.java:268)
at oracle.xml.parser.v2.XMLParser.parse(XMLParser.java:149)
at oracle.apps.xdo.template.fo.FOProcessingEngine.process(FOProcessingEngine.java:320)
at oracle.apps.xdo.template.FOProcessor.generate(FOProcessor.java:1051)
at oracle.apps.xdo.oa.schema.server.TemplateHelper.runProcessTemplate(TemplateHelper.java:5926)
at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3458)
at oracle.apps.xdo.oa.schema.server.TemplateHelper.processTemplate(TemplateHelper.java:3547)
at oracle.apps.fnd.cp.opp.XMLPublisherProcessor.process(XMLPublisherProcessor.java:290)
at oracle.apps.fnd.cp.opp.OPPRequestThread.run(OPPRequestThread.java:157)
[9/2/11 5:32:57 PM] [36822:RT2667735] Completed post-processing actions for request 2667735.
Now, this isn't programme specific as it's affecting all our BI Publisher reports. Also the specific report I am working on has the option to email. I'm finding that the emails still work and when I open the attachment, they are displaying in PDF format correctly - even though the concurrent manager completes with the above warning. The above warning doesn't let me view the output in PDF from Oracle Financials.
Any help would be greatly appreciated.
ThanksMaybe check if Metalink note 764180.1 applies? This appears to be a bug fixed with patch 7669965.
-
Report for replacement stock to be recived from vendor
Hi
I HAVE ONE ISSUE ON ABOUT VENDOR REPLACEMENT STOCK REPORT
EX:.. i have done GR for material-A qty 100...and ihave done MIRO for this ..pur.order..
after 20 days i have return the materai-A ..qty 25..(without cancel the MIRO) with movement tuype 122..but this material should be return from vedor.(subsequent deliver).after some days or weeks ..( bcoz money has already paid to vendor)...like this we many materials ..
for this... i want report for replacement material will be recived from vendor
regards
sesidharHi
already i have done MIRO..
then return to vendor qty 25..(through MIRO...w/o creadit memo
thne again recive the replacement material ..through MIGO (subsequent delivery)
in this case ..need to create credit memo..?
if yes.. pls...send me procedure.
regards
sesidhar -
Exception in thread "main" java.lang.NumberFormatException:For input String
this is a code about arrylist. but when I debug it.it metion:Exception in thread "main" java.lang.NumberFormatException:For input String at java.lang.NumberFormatException.forInputString(numberFomatExceptionio java:48)
at java.lang.Integer.parseInt(integer.java:468)
at java.lang.Integer.parseInt(integer.java:497)
at Get.getInt(manerger.java:208)
at LinkList.insertFirst(manager.java:94)
at manager.main(manager.java;20)
this is my code:
import java.io.*;
import java.lang.*;
public class manager
public static void main(String args[]) throws IOException
LinkList list=new LinkList();
System.out.println("input S can scan the grade\ninput D can delete one entry\ninput U can update the entry\ninput A can add one entry\ninput E can end");
int cr=System.in.read();
switch(cr)
case 'A':
list.insertFirst();break;//this is 20 row
case 'S':
System.out.println("input the s");break;
case 'D':
System.out.println("input the d");break;
case 'U':
System.out.println("input the u");break;
class Link
public int number;
public String name=new String();
public int chs;
public int eng;
public int math;
public Link next;
public Link(int number,String name, int chs,int eng,int math)
this.number=number;
this.name=name;
this.chs=chs;
this.eng=eng;
this.math=math;
public Link()
this(0,"",0,0,0);
public void displayLink()
System.out.println(number + " "+name+ " "+chs+ " "+eng+ " "+math+ " ");
class LinkList
public Link first;
public LinkList()
first = null;
public boolean isEmpty()
return first==null;
public void displayList()
System.out.println("");
Link current=first;
while(current!=null)
current.displayLink();
current=current.next;
System.out.println("");
public Link insertFirst() throws IOException
Get getdata=new Get();
int number=getdata.getInt();//this is 94 row
String name=getdata.getString();
int chs=getdata.getInt();
int eng=getdata.getInt();
int math=getdata.getInt();
Link newLink = new Link(number,name,chs,eng,math);
first=newLink;
return first;
public Link find(int key)
Link current=first;
while(current.number!=key)
if(current.next==null)
return null;
else
current=current.next;
return current;
public Link update(int key) throws IOException
Link current=first;
while(current.number!=key)
if(current.next==null)
return null;
else
System.out.println("Input the first letter of the subject:");
int c=System.in.read();
Get get=new Get();
switch(c)
case 'c':
current.chs=get.getInt();break;
case 'e':
current.eng=get.getInt();break;
case 'm':
current.math=get.getInt();break;
return current;
public float average(char key)
Link current=first;
float total=0;
float average=0;
float counter=0;
if(current==null)
return 0;
while(current!=null)
switch(key)
case 'c':
total=current.chs+current.next.chs;break;
case 'e':
total=current.eng+current.next.eng;break;
case 'm':
total=current.math+current.next.math;break;
current=current.next.next;
counter++;
average=total/counter;
return average;
public Link delete(int key)
Link current=first;
Link previous=first;
while(current.number!=key)
if(current.next==null)
return null;
else
previous=current;
current=current.next;
if(current==first)
first=first.next;
else
previous.next=current.next;
return current;
class Get
public static String getString() throws IOException
System.out.println("Input your name:");
InputStreamReader str = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(str);
String s = br.readLine();
return s;
public static int getInt() throws IOException
System.out.println("Input your data:");
String st = getString();
return Integer.parseInt(st);//this is 208 row
}It may be that the code in getString() returns a
String that ends with a newline. If that is the
problem, you can use
return (Integer.parseInt(st)).trim();1. getString will never return a String ending in newline. BufferedReader.readLine strips off the newline.
2. Even if you had a newline, String.trim doesn't trim newlines.
3. You would need to trim the String, not the int:
return (Integer.parseInt(st.trim()));As JimDinosaur said, you are passing bad data (the value of "st").
In getInt, add this before trying to parse "st":
System.out.println("###"+st+"###");What does it print?
Maybe you are looking for
-
How Do I Get Music into One Grouping?
On my iTunes I have a lot of music. I also have a lot of groupings for one artist. I have two little boxes for Selena Gomez and the Scene under the Artists tab and a bunch of TobyMac. I have found that it makes one more little box for every song that
-
I'm converting from a PC to iMac. On the PC I have many Inbox folders with PR info for distribution. How do I get these folders from the PC to the iMac? I've used the Windows e mail Inbox folders for an easy access filing cabinet for years, as this
-
I think I said everything I needed to in my "Topic" comment. Thank you for any suggestions
-
The/a/an in Library sorting
Hi, I recently downloaded the latest itunes update. During installation, I chose French as the language. Today I noticed that the songs were no longer sorted disregarding the/a/an in the Artist name (ie The Rolling Stones, The Beatles etc are now und
-
Can I watch NCAA hockey on apple tv, I have an american one subscription
Can I watch a NCAA hockey game on my apple tv. I have an American One subscription and want to mirror the game through my apple tv