Help using regex to change strings
I'm writing a utility to move sub folders from computer to computer. I am trying to get regex to work so a string like "d:\\NewScans\\22102\\7-17" would become "\\\\inv108\\data\\users\\clipper\\scan\\22102\\7-17"
so basically "d:\\NewScans\\" needs to become
"\\\\inv108\\data\\users\\clipper\\scan\\" Here is the program I wrote taht accepts the input and out put directories like:
java Paper mover d:\\NewScans \\\\inv108\\data\\users\\clipper\\scan
This is the code I wrote but it doesn't work:
/** Created to move files from a remote bureau to MPCB */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.io.OutputStream.*;
import java.util.regex.*;
public class PaperMover{
private File start_path;
private File destination;
public static void main(String[] args){
if(args[0] != null){
PaperMover m = new PaperMover(args[0].trim(), args[1].trim());
m.move_papers();
else{
System.out.println("no input directory");
System.exit(0);
public PaperMover(String path, String destination){
start_path = new File(path);
this.destination = new File(destination);
public void move_papers(){
File[] listing = start_path.listFiles();
File temp;
String pat = start_path.getAbsolutePath();
Pattern P = Pattern.compile(pat);
for(int i = 0; i<listing.length; i++){
//get the directories IE 20123
try{
if(listing.isDirectory()){
String t = listing[i].getAbsolutePath();
System.out.println(t);
String t2 = P.matcher(t).replaceAll(destination.getAbsolutePath());
System.out.println(t2);
I get string t and t2 to be equal.
I found my troubles!!
Similar Messages
-
How to use type cast change string to number(dbl)?can it work?
how to use type cast change string to number(dbl)?can it work?
Do you want to Type Cast (function in the Advanced >> Data Manipulation palette) or Convert (functions in the String >> String/Number Conversion palette)?
2 simple examples:
"1" cast as I8 = 49 or 31 hex.
"1" converted to decimal = 1.
"20" cast as I16 = 12848 or 3230 hex.
"20" converted to decimal = 20.
Note that type casting a string to an integer results in a byte by byte conversion to the ASCII values.
32 hex is an ASCII "2" and 30 hex is an ASCII "0" so "20" cast as I16 becomes 3230 hex.
When type casting a string to a double, the string must conform the the IEEE 32 bit floating point representation, which is typically not easy to enter from the keyboard.
See tha attached LabView 6.1 example.
Attachments:
TypeCastAndConvert.vi 34 KB -
Using Regex to search strings......
Hey guys,
I'm trying to scan an html file for specific strings. Basically, I just store the entire html file as a one big long string and then use a regex to scan the string for specific keywords that I am looking for. However, I am not all that familiar with regular expressions in java, and, although I have spent a considerable amount of time reading over the tutorials, I can't seem to get my regular expression to produce the results that I want.
+More specifically, what I am trying to scan the html string for is a keyword preceded by a non-alphanumeric character([/W] and followed by a non-alphanumeric character. Also, since the keywords generally represent country names, state names, state abbreviations, city names, and the like.....I really want to make the scan case-insensitive to the case format of the keyword except in the case that the keyword is an abbreviation (i.e., CA, IN, NY,etc. since making this case-insensitive would pick up a lot of garbage, especially in cases like: IN)+_.* As of right now, this is what I am using for my regex(and the results are all over the place):
*String regex = "[/W]+"+"(?i)"+keyword+"[/W]+";*
This just seems wrong! I've played around with it and, lets just say, the results have generally gotten worse. Does anyone have any ideas on how I should correctly format the regex to achieve the goal explained above?? Any and all help would be greatly appreciated. Thanks.A technique I find very useful in writing complex regex's is to split the regex into its parts and work on just the one part at a time. This helps me to easily see that the components match exactly what I think I am matching. Once I have every individual part working it is very easy to join them to create the entire match.
Something like...
String keywordRegex = "";
String nonAlphaCharRegex = "";
//..etc. etc
String fullRegex = keywordRegex + "whateverIwantToMatchBetween" + nonAlphaCharRegex + ... -
Needing help: using Keylistener to change images
I am trying to using the arrow keys to switch between pictures i have but i cant get it to work... mind that im relativly new at java. Here is what i trying to do:
starts at pic1: press up: frame now has pic2: press down: frame now shows pic1
my code so far:
public class test2 {
static JFrame frame;
static int position = 0;
public static void main(String args[]){
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("Frame Title");
JMenuBar menuBar = new JMenuBar();
JMenu menuFile = new JMenu("File");
JMenu menuHelp = new JMenu("Help");
JMenuItem menuFileExit = new JMenuItem("Exit");
JMenuItem menuFilePlay = new JMenuItem("New");
JMenuItem menuFileAbout = new JMenuItem("About");
JMenuItem menuFileHelp = new JMenuItem("Help");
menuFile.add(menuFilePlay);
menuHelp.add(menuFileAbout);
menuHelp.add(menuFileHelp);
menuFile.add(menuFileExit);
menuBar.add(menuFile);
menuBar.add(menuHelp);
frame.setJMenuBar(menuBar);
frame.setSize(1025, 769);
JLabel temp3 = new JLabel(new ImageIcon("EQ2_000000.gif"));
JPanel temp4 = new JPanel();
temp4.add(temp3);
frame.getContentPane().add(temp4);
frame.setVisible(true);
frame.setIconImage(new ImageIcon("bear.gif").getImage());
menuFileExit.addActionListener
new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
menuFileAbout.addActionListener
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame About = new JFrame("About");
About.setSize(200, 200);
About.setIconImage(new ImageIcon("bear.gif").getImage());
JLabel temp = new JLabel(new ImageIcon("bear.gif"));
JPanel temp2 = new JPanel();
temp2.add(temp);
About.setContentPane(temp2);
About.setVisible(true);
menuFileHelp.addActionListener
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame About = new JFrame("Help");
About.setSize(200, 200);
About.setIconImage(new ImageIcon("bearr.gif").getImage());
About.setVisible(true);
frame.addWindowListener
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.addKeyListener
new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
switch (ke.getKeyCode()) {
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_UP:
frame.getContentPane().removeAll();
position = position + 1;
JLabel temp7 = new JLabel(new ImageIcon("pics/EQ2_00000" + position + ".gif"));
JPanel temp8 = new JPanel();
temp8.add(temp7);
frame.getContentPane().add(temp8);
System.out.print(" u, " + position );
break;
case KeyEvent.VK_DOWN:
frame.getContentPane().removeAll();
position = position - 1;
JLabel temp5 = new JLabel(new ImageIcon("pics/EQ2_00000" + position + ".gif"));
JPanel temp6 = new JPanel();
temp6.add(temp5);
frame.getContentPane().add(temp6);
System.out.print(" d, " + position);
}import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class KeyControl
BufferedImage[] images;
int imageIndex;
JLabel label;
public KeyControl()
loadImages();
imageIndex = 0;
label = new JLabel(new ImageIcon(images[0]));
//label.requestFocusInWindow();
registerKeys(label);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(label);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
private void changeImage(int index)
label.setIcon(new ImageIcon(images[index]));
label.repaint();
private Action up = new AbstractAction()
public void actionPerformed(ActionEvent e)
imageIndex = (imageIndex - 1) % images.length;
if(imageIndex < 0)
imageIndex = images.length - 1;
changeImage(imageIndex);
private Action down = new AbstractAction()
public void actionPerformed(ActionEvent e)
imageIndex = (imageIndex + 1) % images.length;
changeImage(imageIndex);
private void registerKeys(JComponent c)
c.getInputMap().put(KeyStroke.getKeyStroke("UP"), "UP");
c.getActionMap().put("UP", up);
c.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "DOWN");
c.getActionMap().put("DOWN", down);
private void loadImages()
String[] fileNames = { "greathornedowl.jpg", "mtngoat.jpg" };
images = new BufferedImage[fileNames.length];
for(int j = 0; j < images.length; j++)
try
URL url = getClass().getResource("images/" + fileNames[j]);
images[j] = ImageIO.read(url);
catch(MalformedURLException mue)
System.err.println("url: " + mue.getMessage());
catch(IOException ioe)
System.err.println("read: " + ioe.getMessage());
public static void main(String[]args)
new KeyControl();
} -
Need help using Regex to parse street addresses
Let me start off by stating three things:
I suck at regex,
I've googled this and didn't come up with an answer, and
I'm on ColdFusion 10
I have a form with an autocomplete input that allows a user to enter street addresses (either in full like "123 Main St, Mayberry" or in part like "123 Main St" or "Main St" or "Main St, Mayberry". I need to tell if the user has provided a street number or not at the beginning of the value they enter into the input. I'm trying to test the input value with this code:
<cfif ReFind("^([0-9]{1-5})",q)>
<!--- address starts with a number --->
<cfelse>
<!--- address doesn't start with a number --->
</cfelse>
q is the input value being passed into my code from the autocomplete function.
x should be either 0 (if the input value doesn't start with a number) or a positive integer (if the input value does start with a number).
Basically, I just need to know if the input value starts with one to five digits.
I suppose I could just do something like:
<cfif Val(q)>
Am I better off using a regex, and if so, what am I doing wrong with the one I've tried?
-Carl V.Oh man do I feel stupid! I read the Adobe docs several times, and understood I needed a comma there, but I had a brain fart when I actually typed my code. Thanks for the minor *headslap*!
I had tried it without the parantheses before, and had added them when trying to troubleshoot. I'll remove them from my working code.
And I will check out your blog series on Regex.
-Carl V. -
Search given string array and replace with another string array using Regex
Hi All,
I want to search the given string array and replace with another string array using regex in java
for example,
String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
String fromValue[] = {"you", "search", "for", "any"}
String toValue[] = {"me", "dont search", "never", "trip"}
so the string "you" needs to be converted to "me" i.e you --> me. Similarly
you --> me
search --> don't search
for --> never
any --> trip
I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
One Single regular expression which matches the pattern and solve the issue.
the output should be as:
If me wish to don't search never trip etc...,
Please help me to resolve this.
Thanks In Advance,
KathirAs stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
import java.util.regex.*;
public class Test
static final List<String> oldWords =
Arrays.asList("you", "search", "for", "any");
static final List<String> newWords =
Arrays.asList("me", "dont search", "never", "trip");
public static void main(String[] args) throws Exception
String str = "If you wish to search for any of these characters, "
+ "they must be preceded by the character to be interpreted";
System.out.println(doReplace(str));
public static String doReplace(String str)
Pattern p = Pattern.compile("\\b\\w+\\b");
Matcher m = p.matcher(str);
StringBuffer sb = new StringBuffer();
while (m.find())
int pos = oldWords.indexOf(m.group());
if (pos > -1)
m.appendReplacement(sb, "");
sb.append(newWords.get(pos));
m.appendTail(sb);
return sb.toString();
} This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays). -
How To Color a Text string using Regex (java.util.regex)
Hello,
How can I color a text string using regex class in 1.4?Yes, did you notice it said something about incredibly vague functionality?
Let me break it down for you
> How can I color a text string
Strings do not have color... You can color a component (a label, a button), but you can't color a string
> using regex class in 1.4?
Using a regular expression? How would a regular exression color anything? Do you have embedded color codes? Are you searhing a string for some secret word?
What are you talking about? -
When I copy and paste from Word to my e-mail using Firefox it changes the font and spacing to single space and 10pt.
It just started doing this a month ago.
It does not do it when I am on my laptop or using Explorer.
Help, I hate explorer.If this were a project that I was involved in, I would recapture the media at the correct frame rate and rebuild the sequences correctly.
Moving from production, to post production, to delivery is a series of steps, and the success of any particular step is based on having all the preceding steps done correctly.
Shortcuts and workarounds tend to create awkward and difficult problems, that often only surface late in the process.
MtD -
Extract the numbers in string using regex
Hi,
How to extract the numers in string using regex?.
Already i tried split up the string using [\\s]
For ex: "Uting Tatk and Window Panet 15"
it gives the ans 15.
if the string is
For ex: "Uting Tatk and Window Panet 15 New!"
i can't find the number.
so plz give me some idea to get the number frm String.
ThanksI am developing a java project to extract Table of
content in a particular
PDF.
i extracted all topics.
then i want 2 extract page number from dat extracted
TOC.
if the TOC ends with number then i can easily find
out the number
but in vain if the TOC ends with like this
"Uting Tatk and Window Panet 15 New!".
i could n't find the page number.What will you do if it says:
"15 ways to find topics 42 new" -
I need an execution of commands after the reply from the instrument matches with the string I provided for that i used true or false string match VI on which the true string the matching command and the string is the reply from the instrument. And I put the further executionable commands in frame after frame of sequence loop in the true of the case structure. Amd finally I given all the output strings to the concatenate string to get all the replies as one loop. But when I execute the program the desired result is not available. So kindly please help me to overcome this problem.
Attachments:
basic serial with changes.vi 24 KBYou VI makes absolutely no sense and I would recommend you start with a few simple LabVIEW tutorials before trying to tackle this.
What is the point of the FOR loop with 1 iteration, it might as well not even be there, same difference.
Why is there an abort primitive in the FOR loop, this mean the program will unconditionally stop abort before any downstream code will ever go into action. The program will never get past the FOR loop.
You created a circular data dependency and LabVIEW inserted a feedback node automatically, making things even worse. (see also)
You need to learn about dataflow, execution order, and data dependency.
You need to learn about the various types of tunnels (plain, autoindexing, etc.)
There is a tremendous amount of duplicate code. Large code sections are the same, differeing only by a string. You should only have one copy of that code inside a proper state machine. Have a look at the design templates and examples that ship with LabVIEW.
LabVIEW Champion . Do more with less code and in less time . -
Sql aggregate help using month
Hello guys.. I need your help in the below query..
Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
create table test_12 ( co_cd varchar2 (10),
dt date,
sale number(10));
insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','01-09-2000','250.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','04-09-2000','350.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','01-12-2000','450.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('CO','01-09-2000','950.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('CO','05-09-2000','250.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('TI','07-09-2000','750.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','09-09-2000','150.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('AB','02-09-2000','850.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('AB','01-09-2000','250.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('TI','04-09-2000','850.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('LC','06-09-2000','550.00');
insert into test_12 (CO_CD,DT,SALE) VALUES ('CO','02-09-2000','250.00');
COMMIT;
the target data should be aggregated sales for last 15 months of data for each company code
CO_CD JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
CO 950 250 0 0 0
TI 0 0 850
thanksHi,
Thanks for posting the CREATE TABLE and INSERT statements. That really helps to understand the problem, and to make sure that the answers actually do work.
If you post code that doesn't work, then it's not so helpful. None of your INSERT statements work for me. They may work for you, depeneing on you NLS settings, but you sshouldn't use strings, such as '01-09-2000' in place of a DATE. Use TO_DATE to convert string like that into DATEs.
Also, don't INSERT strings like '250.00' in place of a NUMBER. Lose the quotes. so it would be better if you posted statements like this:
insert into test_12 (CO_CD,DT,SALE) VALUES ('LC', TO_DATE ('01-09-2011', 'MM-DD-YYYY'), 250.00);How do you get the results you posted for that sample data? It looks like none of the dts are in the last 120 months, let alone the last 15 months.
Why do you want output rows for co_cds 'CO' and 'TI', but not for 'AB' and 'LC'?
Please format your output, so people can tell which number is in which column. Whenever you post formatted text (such as query results) on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
If the "last 15 months" means the 15 consecutive months ending with the current calendar month, then you can do something like this:WITH got_month_num AS
SELECT co_cd
, MONTHS_BETWEEN ( TRUNC (SYSDATE, 'MONTH')
, TRUNC (dt, 'MONTH')
) AS month_num
, sale
FROM test_12
WHERE dt >= ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), -14) -- For efficiency
AND dt < ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), 1)
SELECT *
FROM got_month_num
PIVOT ( SUM (sale)
FOR month_num IN ( 0 AS this_month
, 1 AS "1 Month Ago"
, 2 AS "2 Months Ago"
, 14 AS "14 Months Ago"
ORDER BY co_cd
If "the last 15 months" means something else, then just change the definition of month_num in the sub-query.
If you want less generic column names (e.g. 'APR_2011') that change automatically, depending on when the query is run and/or what data is found in the table, then you have to use dynamic SQL. This isn't very hard in SQL*Plus: you can do a separate preliminary query to set sione substritution varaibles, and then use those variables as the column alaises in the PIVOT clause. -
Opening a new form using a different connect string
Hi All
I have the following requirement. I want to open an new form (when button pressed) using a different connect string. I am planning to use open form so that the new form has its own session. But I donot want the new form to connect to the same database. How do I pass the database that I want to connect using open form.
Rgds
Arvind BalaramanThe only way to change the connection is to execute the built-in LOGIN and connect to the desired database. You cannot pass this through the OPEN_FORM built-in.
Example:
LOGOUT;
LOGON(uname, upass || '@' || conn_str);
However, be aware that this will impact the first form too. This is expected behavior.
See Oracle Bug 5004661 or the Forms Online Help for more details.
http://www.oracle.com/webapps/online-help/forms/10g/state?navSetId=_&navId=3&vtTopicFile=designing_forms/multform_db/at0505.html -
Hi,
I want to detect the presence of "fromCharCode" in a String.
But only when it is not preceded by "String." and not followed by "(34)".
I have already managed to do the "String." with this regex: (?<!string\.)fromCharCode --> uses the negative look behind
This will detect the "fromCharCode", but not when it is preceded by "String.".
But I don't know how to do the "(34)" ?
Can somebody help me with this?thanks, but the problem with this regex now is that "fromCharCode" is not detected in the String fromCharCode(34) and the String String.fromCharCode.
The text "fromCharCode" must only be detected when not preceded by "String." AND not followed by "(34)".
Can you do this? -
Validating input if nonalphanumeric character without using regex
Hi Guys,
I am trying to validate if the user input does not contain any alphanumeric characters such as (A-Z, a-z, 0-9)... The problem was solved through this forum by using regex....
Unfortunately I'm developing with Blackberry (RIM IDE) but it seems that it doesn't support java.util.regex.Pattern and java.util.regex.Matcher;
Is there any other solutions to this problem? Can java.util.regex.* be added to Blackberry JDE?
If anybody knows any solution to this problem...Please let me know...
Please help... Thanks in advancepublic boolean method(String s) {
loop over String {
if (current char is not a valid char) {
return false;
return true;
} -
Using RegEx in Subscription Criteria
Using RegEx in Subscription Criteria
Hello
I want to use RegEx expression for filtering in my Subscription criteria, as follows:
Let say all the monitor I created start with same set of characters i.e.
"My Monitor"
Therefore I have several monitors called
My Monitor ABC
My Monitor 123
My Monitor XYZ
Therefore as part of the Subscription Criteria, under "with a specific name" I currently have
My Monitor%
The % meaning any one or more characters. That works find I receive notifications for alerts from all of the monitors with the above names.
Now what I want to do is keep this one subscription criteria but exclude notifications from say My Monitor 123. I still want to receive notifications from the other two monitors, therefore I was thinking this is a case for RegEx
First question is can I use RegEx in the criteria "with a specific name" field? I guess I am already doing the with the % however, I believe that is an SQL expression rather than a true RegEx expression?
The following blog has some detailed information
http://social.technet.microsoft.com/Forums/en-US/operationsmanagergeneral/thread/ac0bf65f-f562-4f8c-b624-5fbe7ee2e795/
I am not clear if this would work in my case, for example it states the ^ character is used to denote NOT. Based on this I was thinking about changing the above
My Monitor%
To
My Monitor%[^123]
Will the above work, is it the correct syntax?
Any advise, most welcome
Thanks you all
ErnieHello Yury,
Thanks again for your help. Your solution worked, however with a slight difference as I discovered something else while testing.
Basically the example above
My Monitor [^1][^2][^3]%
Only takes into account the First character of the word/phrase for example, using the above filer, the results were
My Monitor ABC - pass
My Monitor 123 - no pass
My Monitor XYZ - pass
My Monitor 222 - pass
My Monitor XY3 - pass
I therefore had to add an _ as part of the filter meaning one character, therefore using the above example if I want to block
My Monitor 123
My filter would be as follows
My Monitor [^1][^_2][^__3]%
i.e. 1 being the first character, 2 being the second character by placing any single character in front of it using the _ then 3 being the third character by placing and two characters
in from of it by using two _ characters i.e. __
Thanks again, I could not of figured it out without your help
Ernie
Maybe you are looking for
-
Isight not working in Ichat/ yahoo
I sight works fine in photo booth but when i try to use it in I chat it wil lsend a request, the other person accepts and then it comes back saying i never accpeted.... Same thing happenes on yahoo .. I see the video image its trying to send to them
-
MAC Files are not Visible when logged in on Windows
HEllo I installed 10.5 with Boot camp and Windows XP successfully on my MAc Mini (1GB RAM). When i log on to MAC i see the Windows partitoned HDD and its contents however when i log on to windows i cant see the MAC Partitoned HDD in windows explorer.
-
Lens Correction Profiles: Unable to locate matching profiles automatically
In LR3, I can't seem to load the auto lens correction profiles for my Canon lenses, many of which should be readily available. I used the 24-70L 2.8 USM lens and the 50mm 1.4 lenses on a recent shoot and the profiles can't be found. Is there a place
-
After uprade from LR 3 to LR 4 Photoshop Elements does not start. I deleted all imported apps in the editor list. But it did not help. When I export the photo - e.g. to desktop - and say "open with..." in the export window then ps9 starts.
-
Help plz!!!! iPod touch isn't compatible with speakers!!
My new iPod touch says that it isn't compatible with my iHome. But, when I went to the Apple store, the guy told me that there was a converter I could buy that would fix this. But then I went to Best Buy, and the guy told me something completely diff