Pattern regex matching advice needed
Hi All,
Many thanks for any/all advice :)
Here's my problem. I'm trying to scan a text file for...
\foo(parm1|parm2)
...in which I want the sub-string "parm1|parm2"
So... [\\]foo matches the first section. No problem...
It's when I try adding the '(' or ')' that I'm getting errors.
java.util.regex.PatternSyntaxException: Unclosed character class near index
[\]foo(.*)
Basically, I'm trying to create a pattern, which can recognize \foo(parms), and extract the parms sections.
Any ideas?
Yes you can do this. It is not allowed in basic java but there are always around the syntax rules. What you can do it use AspectJ plugin in for eclipse and define a cutpoint and make it extend from two classes. What it does is it parses the byte code and inputs the code directly into the byte code. It's pretty neat.
A simplier approach would be to have two classes A and B. Have A extend BASE and then have B Extend A and then therefore B "isa" A and a BASE.
Hope this helps.
Similar Messages
-
Lexical search using Pattern and Matcher class
Hi Folks,
Need some help with the following Query. I want to find out how I can implement
the following by using Pattern / Matcher classes.
I have a query that returns the following set of strings,
aa
abc
def
ghi
glk
gmonalaks
golskalskdkdkd
lkaldkdldldkdld
mladlad
n33ieler
What I would like do is to find out any string that starts with g and Lexical occurs after ghi. So this will return
ghi / glk / gmonalaks / golskalskdkdkd
How can I accomplish the above, by using the following two classes.
Pattern datePattern = Pattern.compile();
Matcher dateMatcher = datePattern.matcher();
Thanks a bunch...
_Shoe Maker..Nothing in your specification requires a regex. Loop though the strings until you find the string "ghi". Then continue looping though the strings outputting those where the first characters is 'g' .
-
Capture regex match as a variable?
Hello!
I have this program and I basically want to match a part of a string and grab the match as a variable. In this case, the string I need to parse is 'foo'.
Here is what I have:
public class Test
public static void main(String[] args)
// link <link> format
String foo = "http://www.foo.com <http://www.foo.com>";
String the_regex = "\\<(http://[^\\>]*)\\>";
String the_replacement = "<a href=\"$1\">$1</a>";
System.out.println(foo.replaceAll(the_regex,the_replacement));
}$1 (sorta like PERL) should be the captured text from the_regex
Any ideas?
Thanks in advance.Dubwai - I think I got it, thanks for the guidance. Here is what I used, and it seems to work. Thanks!
public class Test
public static void main(String[] args)
String foo = "http://www.foo.com <http://www.boo.com>";
String regex="\\<(http://[^\\>]*)\\>";
Pattern p = Pattern.compile(regex);
Matcher m1 = p.matcher(foo);
while (m1.find())
System.out.println("The site = " + m1.group(1));
} -
Util.regex matcher.groupCount()
Hello all. I am trying to parse some text using regex. What I am parsing may have 1 or more matches per line and I need access to each match independantly. The code shown below works well in finding all matches except for the m.groupCount() always returns 0. Thus I can't to anything with individual matches. How can get the groupCount() to function properly?
Thanks in advance.
f (currentLine.startsWith("LOCUSLINK")){
line++;
String pattern = "[0-9]+";
Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(currentLine);
while(m.find()) {
int count = m.groupCount();
for (int x = 0; x <= m.groupCount(); x++)
System.out.println(line+"="+x+"="+count);There aren't capturing groups and really don't need to use in this case.
Try this simple way:
String re = "\\d+";
Matcher m = Pattern.compile(re).matcher(anyString);
for (int j=1; m.find(); j++) {
System.out.println("matching " + j + ": " + m.group(0));
.. -
Pattern and Matcher of Regular Expressions
Hello All,
MTMISRVLGLIRDQAISTTFGANAVTDAFWVAFRIPNFLRRLFAEGSFATAFVPVFTEVK
ETRPHADLRELMARVSGTLGGMLLLITALGLIFTPQLAAVFSDGAATNPEKYGLLVDLLR
LTFPFLLFVSLTALAGGALNSFQRFAIPALTPVILNLCMIAGALWLAPRLEVPILALGWA
VLVAGALQLLFQLPALKGIDLLTLPRWGWNHPDVRKVLTLMIPTLFGSSIAQINLMLDTV
IAARLADGSQSWLSLADRFLELPLGVFGVALGTVILPALARHHVKTDRSAFSGALDWGFR
TTLLIAMPAMLGLLLLAEPLVATLFQYRQFTAFDTRMTAMSVYGLSFGLPAYAMLKVLLP
I need some help with the regular expressions in java.
I have encountered a problem on how to retrieve two strings with Pattern and Matcher.
I have written this code to match one substring"MTMISRVLGLIRDQ", but I want to match multiple substrings in a string.
Pattern findstring = Pattern.compile("MTMISRVLGLIRDQ");
Matcher m = findstring.matcher(S);
while (m.find())
outputStream.println("Selected Sequence \"" + m.group() +
"\" starting at index " + m.start() +
" and ending at index " m.end() ".");
Any help would be appreciated.Double post: http://forum.java.sun.com/thread.jspa?threadID=726158&tstart=0
-
Hey,
I'm trying to use the pattern and matcher to replace all instances of a website
address in some html documents as I process them and post them. I'm
including a sample of some of the HTML below and the code I"m using to
process it. For some reason it doesn't replace the sites in the underlying
images and i can't figure out what I'm doing wrong. Please forgive all the
unused variables, those are relics of another way i may have to do this if i
can't get the pattern thing to work.
Josh
public static void setParameters(File fileName)
FileReader theReader = null;
try
System.out.println("beginning setparameters guide2)");
File fileForProcessing=new File(fileName.getAbsolutePath());
//wrap the file in a filereader and buffered reader for maximum processing
theReader=new FileReader(fileForProcessing);
BufferedReader bufferedReader=new BufferedReader(theReader);
//fill in data into the tempquestion variable to be populated
//Set the question and answer texts back to default
questionText="";
answerText="";
//Define the question variable as a Stringbuffer so new data can be appended to it
StringBuffer endQuestion=new StringBuffer();//Stringbuffer to store all the lines
String tempQuestion="";
//Define new file with the absolutepath and the filename for use in parsing out question/answer data
tempQuestion=bufferedReader.readLine();//reads the nextline of the question
String tempAlteredQuestion="";//for temporary alteration of the nextline
//while there are more lines append the stringbuffer with the new data to complete the question buffer
StringTokenizer tokenizer=new StringTokenizer(tempQuestion, " ");//tokenizer for reading individual words
StringBuffer temporaryLine; //reinstantiate temporary line holder each iterration
String newToken; //newToken gets the very next token every iterration? changed to tokenizer moretokens loop
String newTokenTemp; //reset newTokenTemp to null each iterration
String theEndOfIt; //string to hold everything after .com
char[] characters; //character array to hold the characters that are used to hold the entire link
char lastCharChecked;
Pattern thePattern=Pattern.compile("src=\"https:////fakesite.com//ics", Pattern.LITERAL);
Matcher theMatcher=thePattern.matcher(tempQuestion);
while(tempQuestion!=null) //every time the tempquestion reads a newline, make sure you aren't at the end
String theReplacedString=theMatcher.replaceAll("https:////fakesite.com//UserGuide/");
// temporaryLine=new StringBuffer();
//add the temporary line after processed back into the end question.
endQuestion.append(theReplacedString); //temporaryLine.toString());
//reset the tempquestion to the newline that is going to be read
tempQuestion=bufferedReader.readLine();
if(tempQuestion!=null)
theMatcher.reset(tempQuestion);
/*newTokenTemp=null;
while(tokenizer.hasMoreTokens())
newToken=tokenizer.nextToken(); //get the next token from the line for processing
System.out.println("uhhhhhh");
if(newToken.length()>36) //if the token is long enough chop it off to compare
newTokenTemp=newToken.substring(0, 36);
if(newTokenTemp.equals("src=\"https://fakesite.com"));//compare against the known image source
theEndOfIt=new String(); //intialize theEndOfIt
characters=new char[newToken.length()]; //set the arraylength to the length of the initial token
characters=newToken.toCharArray(); //point the character array to the actual characters for newToken
lastCharChecked='a'; // the last character that was compared
int x=0; //setup the iterration variable and go from the length of the whole token back till you find the first /
for(x=newToken.length()-1;x>0&&lastCharChecked!='/';x--)
System.out.println(newToken);
//set last char checked to the lsat iterration run
lastCharChecked=characters[x];
//set the end of it to the last char checked and the rest of the chars checked combined
theEndOfIt=Character.toString(lastCharChecked)+theEndOfIt;
//reset the initial newToken value to the cut temporary newToken root + userguide addin, + the end
newToken=newTokenTemp+"//Userguide"+theEndOfIt;
//add in the space aftr the token to the temporary line and the new token, this is where it should be parsed back together
temporaryLine.append(newToken+" ");
//add the temporary line after processed back into the end question.
endQuestion.append(temporaryLine.toString());
//reset the tempquestion to the newline that is going to be read
tempQuestion=bufferedReader.readLine();
//reset tokenizer to the new temporary question
if(tempQuestion!=null)
tokenizer=new StringTokenizer(tempQuestion);
//Set the answer to the stringbuffer after converting to string
answerText=endQuestion.toString();
//code to take the filename and replace _ with a space and put that in the question text
char theSpace=' ';
char theUnderline='_';
questionText=(fileName.getName()).replace(theUnderline, theSpace);
catch(FileNotFoundException exception)
if(logger.isLoggable(Level.WARNING))
logger.log(Level.WARNING,"The File was Not Found\n"+exception.getMessage()+"\n"+exception.getStackTrace(),exception);
catch(IOException exception)
if(logger.isLoggable(Level.SEVERE))
logger.log(Level.SEVERE,exception.getMessage()+"\n"+exception.getStackTrace(),exception);
finally
try
if(theReader!=null)
theReader.close();
catch(Exception e)
<SCRIPT language=JavaScript1.2 type=text/javascript><!-- if( typeof( kadovInitEffects ) != 'function' ) kadovInitEffects = new Function();if( typeof( kadovInitTrigger ) != 'function' ) kadovInitTrigger = new Function();if( typeof( kadovFilePopupInit ) != 'function' ) kadovFilePopupInit = new Function();if( typeof( kadovTextPopupInit ) != 'function' ) kadovTextPopupInit = new Function(); //--></SCRIPT>
<H1><IMG class=img_whs1 height=63 src="https://fakesite.com/ics/header4.jpg" width=816 border=0 x-maintain-ratio="TRUE"></H1>
<H1>Associate Existing Customers</H1>
<P>blahalbalhblabhlab blabhalha blabahbablablabhlablhalhab.<SPAN style="FONT-WEIGHT: bold"><B><IMG class=img_whs2 height=18 alt="Submit aIf you use just / it misinterprets it and it ruins
your " " tags for a string. I don't think so. '/' is not a special character for Java regex, nor for Java String.
The reason i used
literal is to try to force it to directly match,
originally i thought that was the reason it wasn't
working.That will be no problem because it enforces '.' to be treated as a dot, not as a regex 'any character'.
Message was edited by:
hiwa -
String.matches vs Pattern and Matcher object
Hi,
I was trying to match some regex using String.matches but for me it is not working (probably I am not using it the way it should be used).
Here is a simple example:
/* This does not work */
String patternStr = "a";
String inputStr = "abc";
if(inputStr.matches( "a" ))
System.out.println("String matched");
/* This works */
Pattern p = Pattern.compile( "a" );
Matcher m = p.matcher( "abc" );
boolean found = false;
while(m.find())
System.out.println("Matched using Pattern and Matcher");
found = true;
if(!found)
System.out.println("Not matching with Pattern and Matcher");
Am I not matches method of String class properly?
Please throw some lights on this.
Thank you.String.matches looks at the whole string.
bsh % "abc".matches("a");
<false>
bsh % "abc".matches("a.*");
<true> -
Question on regex Matcher (group number)
HI, everybody
I am writing a program on replacement like the one below.
String regex = "(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)";
String original = "ABCDEFGHIJKL";
String replacement = "$12";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(original);
String result = m.replaceFirst(replacement);What I actually want is to take out the first group, in this case an "A", and append a character "2" after it.
The result I am expecting is "A2". But the result I get is "L". For the regex engine takes it as the 12th group.
What should I do to remove the ambiguity.
Thanks.In such case, use $1\\2.
-
it seems like j2sdk1.4.2b has some serious regex matching bug with strings that contain unicode characters. In my case, the string contained some Turkish chars.
regex is simple <[^>]*> which matches string runs that are enclosed in <>
(ex. <field>)
although the matching is successful with j2sdk1.4.1_02, it just doesn't match unicode containing text with 1.4.2b
What do you think? Is this a bug or could I be missing something?ahmeti, did you submit a bug report on this? Because it definitely is a bug in the Pattern class, I finally figured out. They added a new node type to make matching ASCII characters in character classes more efficient, but they screwed up the match condition: it always returns false if the character it's looking at is not ASCII, even if the class has been negated. I'll go ahead submit a report myself unless I hear from you.
-
Hi,
Jdev 11.1.1.0.31.51.56
If somebody of you get the following trace stack when running a jspx using ViewCriteriaRow.setOperator :
There is bug 7534359 and metalink note 747353.1 available.
java.lang.NullPointerException
at java.util.regex.Matcher.getTextLength(Matcher.java:1140)
at java.util.regex.Matcher.reset(Matcher.java:291)
at java.util.regex.Matcher.<init>(Matcher.java:211)
at java.util.regex.Pattern.matcher(Pattern.java:888)
at oracle.adfinternal.view.faces.model.binding.FacesCtrlSearchBinding._loadFilter
CriteriaValues(FacesCtrlSearchBinding.java:3695)
Truncated. see log file for complete stacktrace
Workaround:
If you use
vcr.setAttribute("Job",job);
or
vcr.setAttribute("Job","="+job);
than add following line of code:
vcr.setOperator("Job","="); regards
PeterHi,
useful to mention that this happens when setting the equal operator or LIKE operator
vcr.setAttribute("Job","= '"+job+"'");
or
vcr.setOperator("Job","=");
Frank -
Patterns and Matcher.find()
I would be really grateful for some assistance on this. I have been at this for three hours and can't get it correct.
I have a string such as this: "Hello this is a great <!-- @@[IMAGINE_SPACIAL_VECTOR]@@ --> little string"
I want to use RegEx, Pattern and Matcher.find() to extract "IMAGINE_SPACIAL_VECTOR" ie. the text between "<!-- @@[" and "]@@ -->"
Thanks in advance for your helpimport java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
String data = "Hello this is a great <!-- @@[IMAGINE_SPACIAL_VECTOR]@@ --> little string";
Matcher matcher = Pattern.compile("<!-- @@\\[(.*?)]@@ -->").matcher(data);
while (matcher.find()) {
System.out.println(matcher.group(1));
}Might not be the best way, but it works.
Kaj -
Regex Matching Involving Unicode
Hi,
I'm trying to do a regex match using boost::regex and followed the instructions on http://niemannross.com/developer/wiki/index.php?title=Using_boost_regular_expressions_(re gexp)_in_InDesign_CS/CS2/CS3_plug-in_code
My regex needs to match a line that ends with punctuation characters and return the string that excluding the ending punctuation characters.
ex. home -> home
ex regex: (.*?)[ \\x{201C}\\x{201D}]+$
however it does not match the line.
I tried using boost::u32regex but i'm getting a boost::icu_regex_traits::translate_nocase symbols not found error on linking.
How can I go around this problem?
Thanks in advance!
-- JeffEscaping the backslash in '\x' is necessary for your programming language, otherwise it is interpreted as a 'real' hex character. So as it is, this feeds '\x{201C]' into your program, rather than the literal 0x201C code. (It'd be a syntax error for C, but you get the point.)
However: because this is an expression IN GREP inside your running program, I think you have to escape it again, so it might need double double backslashes. Scripts suffer the same problem. -
How to Use Pattern and Matcher class.
HI Guys,
I am just trying to use Pattern and Matcher classes for my requirement.
My requirement is :- It should allow the numbers from 1-7 followed by a comma(,) again followed by the numbers from
1-7. For example:- 1,2,3,4,5 or 3,6,1 or 7,1,3 something like that.
But it should not allow 0,8 and 9. And also it should not allow any Alphabets and special characters except comma(,).
I have written some thing like..
Pattern p = Pattern.compile("([1-7])+([\\,])?([1-7])?");
Is there any problem with this pattern ??
Please help out..
I am new to pattern matching concept..
Thanks and regards
Sudheerok guys, this is how my code looks like..
class PatternTest
public static void main(String[] args)
System.out.println("Hello World!");
String input = args[0];
Pattern p = Pattern.compile("([1-7]{1},?)+");
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("Pattern Found");
} else {
System.out.println("Invalid pattern");
}if I enter 8,1,3 its accepting and saying Pattern Found..
Please correct me if I am wrong.
Actually this is the test code I am presenting here.. I original requirement is..I will be uploading an excel sheets containg 10 columns and n rows.
In one of my column, I need to test whether the data in that column is between 1-7 or not..If I get a value consisting of numbers other than 1-7..Then I should
display him the msg..
Thanks and regards
Sudheer -
Regex - match a word except when it's preceeded by another word
Does anyone know how to write a regular expression that will match an occurrence of a word except when it's preceeded by another word? I'm trying to match all occurrences of the word "function" except when it's part of the phrase "end function". Is that possible in a single regular expression?
Maybe this is just how it works, but I'm not sure why a string
with one space wouldn't match but a string with two would.At the beginning of the spaces, the lookbehind causes the match to fail, but then the Matcher bumps ahead one position and tries again. At that point, the lookbehind expression doesn't apply anymore, so you get a match. (You should be able to confirm this by counting the spaces in your output.) I tried using the "aggressive plus" to force it to treat all the spaces as one atom, but that didn't work:
Pattern p = Pattern.compile("(?<!end)(\\s++)function");I don't see how to do this using "pure" lookaround, but if you don't mind matching the preceding word, this will work:
Pattern p = Pattern.compile("(^|(?!end\\b)\\b\\w+ +)function\\b",
Pattern.MULTILINE);Getting pretty hairy, I know, but it matches the word "function", either as the first thing on the line, or preceded by a word that is not "end" (those first couple of \b's are there to ensure that only the whole word "end" will block the match). Here's how you would use this pattern to replace "function" with "method", except when it's preceded by "end":
import java.util.regex.*;
public class Test
public static void main(String[] args)
String target = "end function\n"
+ "function test\n"
+ "functioning test\n"
+ "test function\n"
+ "test function end\n"
+ "end function\n"
+ "ending function\n"
+ "rend function\n"
+ "end functioning\n";
Pattern p = Pattern.compile("(^|(?!end\\b)\\b\\w+ +)function\\b",
Pattern.MULTILINE);
Matcher m = p.matcher(target);
target = m.replaceAll("$1method");
System.out.println(target);
}Here's the output I get:
end function
method test
functioning test
test method
test method end
end function
ending method
rend method
end functioningOf course, if you do know that there will always be exactly one space between "end" and "function", none of this is necessary; you can just use dcostakos's original lookbehind regex--except that I would add word boundaries:
Pattern p = Pattern.compile("(?<!end\\s)\\bfunction\\b"); -
Advice needed on buying iphone as gift
I went to apple store, they do not want to sell iphone to me unless I sign AT&T 2 years plan. I thought AT&T has locked the phone and users must subscribe in order to use it. Why Apple store still not allow me to buy?
Please advice, if I want to buy online iphone for my brother, do I or my brother have obligation to sign out AT&T plan?
One more advice needed, I found the shipment takes weeks, do I have option to arrange for self-collection?
My brother birthday is coming soon, I need above advice urgently.
Thank you very muchTamara wrote:
I'm guessing English is not your first language. It's possible that you misunderstood them. Apple Store employees won't refuse to sell you an iPhone and you don't have to sign up for service in the store.
Well that's not entirely true.
Apple Stores have been instructed not to sell you an iPhone if any of the following is true:
You state that you will not be signing up with AT&T.
You do not have an ID from a US state, also indicating you will not be activating with AT&T
You do not have a credit card
For example, I've seen US Apple Store managers refuse to sell iPhones to European residents because of the AT&T lock-in.
Maybe you are looking for
-
If I want to forward an email, I hit forward, type in the name, tab to start writing something and am unable to do so. The page is outlined with tiny dots (as if it were perforated). When I try to close it down, a small box appears asking if I want t
-
Can't airplay movies - icon disappears when movie starts in iTunes
Hi guys. Had this problem for a little while now. I'm running iTunes 11.4 on Windows 8.1 and an Apple TV in another room. I've had no problems until recently. Anything but movies will play perfectly to the Apple TV. But the second I start a movie, th
-
What is the role of BPEL in EBS Release 12
Hello Everyone, Just I am curious to know the scope of BPEL in Release 12. What are the integration points that R12 offers to work with BPEL. Any information or documents are really appreciated. Thanks Saikrishna
-
I have an Acer Aspire laptop; how do I install the linux upgrade?
I cannot find an updated linux browser; only windows and applemac.
-
Printing from CS5 using mountain lion on imac
I have downloaded mountain lion upgrade from originally using snow leopard for my imac and now CS5 does not print. However Photoshop elements 9 is OK. All other document print OK. Is this an Apple problem or Adobe problem?