Java regex only finding one match - java

I'm using the following regex:
(?<=<((Pswrd>)|([^/]{1,2147483646}?:Pswrd>)))((?s).+?)(?=</(\\1))
And I have the following text to match:
<abc:Pswrd>PASSWORD_ONE</abc:Pswrd>
<Pswrd>PASSWORD_TWO</Pswrd>
I need to match the context of both XML tags but is only working for the second one.
The output is:
PASSWORD_TWO
And it should be:
PASSWORD_ONE
PASSWORD_TWO
It seems the OR is not working for some reason?
String message = " <abc:Pswrd>PASSWORD_ONE</abc:Pswrd>\n" +
" <Pswrd>PASSWORD_TWO</Pswrd>";
String regex = "(?<=<((Pswrd>)|([^/]{1,2147483646}?:Pswrd>)))((?s).+?)(?=</(\\1))";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(message);
while (matcher.find()) {
String group = matcher.group();
System.out.println(group);
}
Thanks
Update: It needs to be the matching group 0.

So in order to either match <Pswd> or <abc:Pswd> or <something:Pswd>, the RegEx would need to look something like <\w*:*Pswrd>. The problem however is that the look behind does not like non-fixed width quantifiers, so you can't create a look behind that caters for a "dynamic"
Instead I would suggest just go for something simple, such as :
(?<=Pswrd>)(.*)(?=<\/)
Essentially here you just look for the last bit of the opening tag (namely "Pswrd>") then you match any thing between that and the closing portion of the tag.

Related

Java Regex pattern that matches in any online tester but doesn't in Eclipse

I have a piece of code that I can't make it working on Eclipse with Java 1.7 installed.
There is a regex expression I want to use to match and extract 2 strings from every match, so I am using 2 groups for this.
I have tested my expression in many websites (online regex testers) and it works for them bust it isn't working on my Java project in Eclipse.
The source string looks like anyone of these:
Formal Language: isNatural
Annotation Tool: isHuman%Human Annotator: isHuman
Hybrid Annotation: conceptType%Hybrid Annotation Tool: conceptType%Hybrid Tagset: conceptType
... and so on.
I want to extract the first words before the ":" and the word after for every match.
The regex I'm using is this:
(\w*\s*\w+):(\s+\w+)%{0,1}
And the snippet of code:
String attribute = parts[0];
Pattern pattern = Pattern.compile("(\\w*\\s*\\w+):(\\s+\\w+)%{0,1}");
Matcher matcher = pattern.matcher(attribute);
OWLDataProperty dataProp = null;
if (matcher.matches()){
while (matcher.find()){
String name = null, domain = null;
domain = matcher.group(1);
name = matcher.group(2);
dataProp = factory.getOWLDataProperty(":"+Introspector.decapitalize(name), pm);
OWLClass domainClass = factory.getOWLClass(":"+domain.replaceAll(" ", ""), pm);
OWLDataPropertyDomainAxiom domainAxiom = factory.getOWLDataPropertyDomainAxiom(dataProp, domainClass);
manager.applyChange(new AddAxiom(ontology, domainAxiom));
}
Does anybody of you know why it's not working?
Many thanks.
When using matches(), you are asking if the string you provided matches your regex as a whole. It is as if you added ^ at the beginning of your regex and $ at the end.
Your regex is otherwise fine, and returns what you expect. I recommend testing it regexplanet.com, Java mode. You will see when matches() is true, when it false, and what each find() will return.
To solve your problem, I think you only need to remove the if (matcher.matches()) condition.

extracting a specific link pattern using java pattern matcher

Let's say I have a link like below along with a bunch of other links
http://testttt.com/met?tag1=x&tag2=y&tag3=z%20a
I would like to extract the entire link if it starts with http://testttt.com/met
I tried doing the following but it didn't work
Pattern pattern = Pattern.compile("http://testttt.com/met?[a-zA-Z][0-9]");
Matcher match = pattern.matcher("http://testttt.com/met?tag1=x&tag2=y&tag3=z%20a");
if (match.find()) {
System.out.println("match found");
}
Why not just use
if (str.startsWith("http://testttt.com/met")) {
...
}
If your string only contains the url, use the answer proposed by Reimeus. If you're trying to extract the url from a bunch of text, you can use this pattern:
Pattern pattern = Pattern.compile("http://testttt\\.com/met\\??[^\\s]*");
It contains all the necessary escapes and and matches everything up to the next whitespace.

Use RegEx in Java to extract parameters in between parentheses

I'm writing a utility to extract the names of header files from JSPs. I have no problem reading the JSPs line by line and finding the lines I need. I am having a problem extracting the specific text needed using regex. After looking at many similar questions I'm hitting a brick wall.
An example of the String I'll be matching from within is:
<jsp:include page="<%=Pages.getString(\"MY_HEADER\")%>" flush="true"></jsp:include>
All I need is MY_HEADER for this example. Any time I have this tag:
<%=Pages.getString
I need what comes between this:
<%=Pages.getString(\" and this: )%>
Here is what I have currently (which is not working, I might add) :
String currentLine;
while ((currentLine = fileReader.readLine()) != null)
{
Pattern pattern = Pattern.compile("<%=Pages\\.getString\\(\\\\\"([^\\\\]*)");
Matcher matcher = pattern.matcher(currentLine);
while(matcher.find()) {
System.out.println(matcher.group(1).toString());
}}
I need to be able to use the Java RegEx API and regex to extract those header names.
Any help on this issue is greatly appreciated. Thanks!
EDIT:
Resolved this issue, thankfully. The tricky part was, after being given the right regex, it had to be taken into account that the String I was feeding to the regex was always going to have two " / " characters ( (/"MY_HEADER"/) ) that needed to be escaped in the pattern.
Here is what worked (thanks to the help ;-)):
Pattern pattern = Pattern.compile("<%=Pages\\.getString\\(\\\\\"([^\\\\\"]*)");
This should do the trick:
<%=Pages\\.getString\\(\\\\\"([^\\\\]*)
Yeah that's a scary number of back slashes. matcher.group(1) should return MY_HEADER. It starts at the \" and matches everything until the next \ (which I assume here will be at \")%>.)
Of course, if your target text contains a backslash (\), this will not work. But you didn't give an indication that you'd ever be looking for something like <%=Pages.getString(\"Fun!\Yay!\")%> -- where this regex would only return Fun! and ignore the rest.
EDIT
The reason your test case was failing is because you were using this test string:
String currentLine = "<%=Pages.getString(\"MY_HEADER\")%>";
This is the equivalent of reading it in from a file and seeing:
<%=Pages.getString("MY_HEADER")%>
Note the lack of any \. You need to use this instead:
String sCurrentLine = "<%=Pages.getString(\\\"MY_HEADER\\\")%>";
Which is the equivalent of what you want.
This is test code that works:
String currentLine = "<%=Pages.getString(\\\"MY_HEADER\\\")%>";
Pattern pattern = Pattern.compile("<%=Pages\\.getString\\(\\\\\"([^\\\\]*)");
Matcher matcher = pattern.matcher(currentLine);
while(matcher.find()) {
System.out.println(matcher.group(1).toString());
}

java Regular expression matching html

solution:
this works:
String p="<pre>[\\\\w\\\\W]*</pre>";
I want to match and capture the enclosing content of the <pre></pre> tag
tried the following, not working, what's wrong?
String p="<pre>.*</pre>";
Matcher m=Pattern.compile(p,Pattern.MULTILINE|Pattern.CASE_INSENSITIVE).matcher(input);
if(m.find()){
String g=m.group(0);
System.out.println("g is "+g);
}
Regex is in fact not the right tool for this. Use a parser. Jsoup is a nice one.
Document document = Jsoup.parse(html);
for (Element element : document.getElementsByTag("pre")) {
System.out.println(element.text());
}
The parse() method can also take an URL or File by the way.
The reason I recommend Jsoup is by the way that it is the least verbose of all HTML parsers I tried. It not only provides JavaScript like methods returning elements implementing Iterable, but it also supports jQuery like selectors and that was a big plus for me.
You want the DOTALL flag, not MULTILINE. MULTILINE changes the behavior of the ^ and $, while DOTALL is the one that lets . match line separators. You probably want to use a reluctant quantifier, too:
String p = "<pre>.*?</pre>";
String stringToSearch = "H1 FOUR H1 SCORE AND SEVEN YEARS AGO OUR FATHER...";
// the case-insensitive pattern we want to search for
Pattern p = Pattern.compile("H1", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(stringToSearch);
// see if we found a match
int count = 0;
while (m.find())
count++;
System.out.println("H1 : "+count);

Java Regex Matcher Question

How do I match an URL string like this:
img src = "https://stackoverflow.com/a/b/c/d/someimage.jpg"
where only the domain name and the file extension (jpg) is fixed while others are variables?
The following code does not seem working:
Pattern p = Pattern.compile("<img src=\"http://stachoverflow.com/.*jpg");
// Create a matcher with an input string
Matcher m = p.matcher(url);
while (m.find()) {
String s = m.toString();
}
There were a couple of issues with the regex matching the sample string you gave. You were close, though. Here's your code fixed to make it work:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TCPChat {
static public void main(String[] args) {
String url = "<img src=\"http://stackoverflow.com/a/b/c/d/someimage.jpg\">";
Pattern p = Pattern.compile("<img src=\"http://stackoverflow.com/.*jpg\">");
// Create a matcher with an input string
Matcher m = p.matcher(url);
while (m.find()) {
String s = m.toString();
System.out.println(s);
}
}
}
First, I would use the group() method to retrieve the matched text, not toString(). But it's probably just the URL part you want, so I would use parentheses to capture that part and call group(1) retrieve it.
Second, I wouldn't assume src was the first attribute in the <img> tag. On SO, for example, it's usually preceded by a class attribute. You want to add something to match intervening attributes, but make sure it can't match beyond the end of the tag. [^<>]+ will probably suffice.
Third, I would use something more restrictive than .* to match the unknown part to the path. There's always a chance that you'll find two URLs on one line, like this:
<img src="http://so.com/foo.jpg"> blah <img src="http://so.com/bar.jpg">
In that case, the .* in your regex would bridge the gap, giving you one match where you wanted two. Again, [^<>]* will probably be restrictive enough.
There are several other potential problems as well. Are attribute values always enclosed in double-quotes, or could they be single-quoted, or not quoted at all? Will there be whitespace around the =? Are element and attribute names always lowercase?
...and I could go on. As has been pointed out many, many times here on SO, regexes are not really the right tool for working with HTML. They can usually handle simple tasks like this one, but it's essential that you understand their limitations.
Here's my revised version of your regex (as a Java string literal):
"(?i)<img[^<>]+src\\s*=\\s*[\"']?(http://stackoverflow\\.com/[^<>]+\\.jpg)"

Categories