I'm using java. And i want to find then replace hyperlink and anchor text of tag <a> html. I knew i must use: replace() method but i'm pretty bad about regex.
An example:
anchor text 1
will be replaced by:
anchor text 2
Could you show my the regex for that purpose? Thanks a lot.
Don't use regex for this task. You should use some HTML parser like Jsoup:
String str = "<a href='http://example.com'>anchor text 1</a>";
Document doc = Jsoup.parse(str);
str = doc.select("a[href]").attr("href", "http://anotherweb.com").first().toString();
System.out.println(str);
You could perhaps use a replaceAll with the regex:
[^<]+
And replace with:
anchor text 2
[^\"]+ and [^<]+ are negated class and will match all characters except " and < respectively.
Related
Hello I need to find all the accent words that aren't inside comments in jsp files.
By example.
<%--This jsp comment have accents áóéí--%>
<html>
<!--This html comment have accents áóéí-->
<h1>This text have accents áóí</h1>
<html>
I need to find the accent letter inside the h1 tag but no the ones inside the comments.
Until now I had the regex to find the comments but I don't know how to negate that part.
This is the Regex I had:
\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>
I try
[ó](?!(\<[!%][ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\%*>))
But it didn't works.
How I could negate that expresion?
It is not feasible to match the inner text of each and every HTML tag with a regex.
I suggest using a Java HTML parser instead. jsoup is a good one. See jsoup cookbook for more examples.
String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>";
Document doc = Jsoup.parse(html);
Element link = doc.select("a").first();
String text = doc.body().text(); // "An example link"
String linkHref = link.attr("href"); // "http://example.com/"
String linkText = link.text(); // "example""
If you need to simply delete them, use Notepad++ regex Find-and-Replace (CHECK the box for ". matches newline"):
Find what:
(--%?>(?:(?!<%--|<!--).)*?)[^-!~##$%^&*()+=.,<>|?/{}\[\]\\""';:\w\s]+
Replace with:
$1
Repeat that Find-and-Replace until it can't find any more matches.
Otherwise, you can just use that regex to find them and deal with them individually.
I'm parsing an HTML file in Java using regular expressions and I want to know how to match for all href="" elements that do not end in a .htm or .html, and, if it matches, capture the content between quotes into a group
These are the ones I've tried so far:
href\s*[=]\s*"(.+?)(?![.]htm[l]?)"
href\s*[=]\s*"(.*?)(?![.]htm[l]?)"
href\s*[=]\s*"(?![.]htm[l]?)"
I understand that with the first two, the entire string between quotes is being captured into the first group, including the .htm(l) if it is present.
Does anyone know how I can avoid this from happening?
You can just rearrange the expression, and move the negative look-ahead to before the capturing:
href\s*[=]\s*"(?!.+?[.]htm[l]?")(.+?)"
Here is a demo.
As a side answer, jsoup is a very good API when dealing with html.
Using jsoup:
Document doc = Jsoup.parse(html);
for(Element link : doc.select("a")) {
String linkHref = link.attr("href");
if(linkHref.endsWith(".htm") || linkHref.endsWith(".html")) {
// do something
}
}
Try this .*\.(?!(htm|html)$)
any character in any number .* followed by a dot . not followed by htm, htmt (?! ... )
I'm trying to extract the text within the title elements and ignore everything else.
I've looked at these articles, but they don't seem to help :\
Regular expression to extract text between square brackets
String Pattern Matching In Java
Java Regex to get the text from HTML anchor (<a>...</a>) tags
The main problem is I am not able to understand what the responders are saying while trying to hack up my own code.
Here is what I've managed from reading the Java API in the Pattern article.
<title>(.*?)</title>
Here's my code to return the title.
String title = null;
Matcher match = Pattern.compile("[<title>](.*?)[</title>]").matcher(this.webPage);
try{
title = match.group();
}
catch(IllegalStateException e)
{
e.printStackTrace();
}
I am getting the IllegalStateException, which says this:
java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.group(Matcher.java:485)
at java.util.regex.Matcher.group(Matcher.java:445)
at BrowserModal.getWebPageTitle(BrowserModal.java:21)
at BrowserTest.main(BrowserTest.java:7)
Line 21 would be "title = match.group();"
What are the pros and cons of the leading Java HTML parsers? lists a bunch of HTML parsers. Parse your HTML to a DOM, then use getElementsByClassName("title") to get the title elements, and grab the text content by looking at its children which should be text nodes.
title = match.group();
This is failing because group() returns the entire matched text. group(1) will return just the content of the first parenthetical group.
[<title>](.*?)[</title>]
The square brackets are just breaking it. [<title>] will match any single character that is an angle bracket or a letter in the word "title".
<title>(.*?)</title>
is better, but will only match a title that is on one line (since . does not, by default, match newlines, and will not match minor variations like
<title lang=en>Foo</title>
It will also fail to find the title correctly in HTML like
<html>
<head>
<!-- <title>Old commented out title</title> -->
<title>Spiffy new title</title>
Try this:-
String title = null;
String subjectString = "<title>TextWithinTags</title>";
Pattern titleFinder = Pattern.compile("<title[^>]*>(.*?)</title>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher regexMatcher = titleFinder.matcher(subjectString);
while (regexMatcher.find()) {
title = regexMatcher.group(1);
}
Edit:- Regex explained:-
[^>]* :- Anything but > is acceptable there. This is used as we can have attributes in the tags.
(.*?) :- Dot represents any character other than newline character. *? represents repeat any number of times, but as few as possible.
For more details on regex, check this out.
This gets the title in just one line of java code:
String title = html.replaceAll("(?s).*<title>(.*)</title>.*", "$1");
This regex assumes the HTML is "simple", and with the "DOTALL" switch (?s) (which means dots also match new-line chars), it will work with multi-line input, and even multi-line titles.
i made a regex to replace "=" after "href" in "a" tags:
output.replaceAll("(<a.*)href=(.*>)", "$1href" + replacemantstring+ "$2");
The problem ist that it only replaces the last occurence of "=" after href ...
What did i do wrong ?
You need to change your wildcards from greedy .* to non-greedy .*?. This will make your regex stop att the first href= match, and therefore match the following occurences too.
If you want to replace link in href paramenter with newURL, then use
output.replaceAll("(?i)(<a[^>]*?\\shref\\s*=)(['"]).*?\\2", "$1$2" + newURL + "$2");
EDIT: If you want to replace just = behind href in <a> tag, then use
output.replaceAll("(?i)(<a[^>]*?\\shref\\s*)=", "$1" + replacement);
I'm trying to get a text within a certain tag. So if I have:
<a href="http://something.com">Found<a/>
I want to be able to retrieve the Found text.
I'm trying to do it using regex. I am able to do it if the <a href="http://something.com> stays the same but it doesn't.
So far I have this:
Pattern titleFinder = Pattern.compile( ".*[a-zA-Z0-9 ]* ([a-zA-Z0-9 ]*)</a>.*" );
I think the last two parts - the ([a-zA-Z0-9 ]*)</a>.* - are ok but I don't know what to do for the first part.
As they said, don't use regex to parse HTML. If you are aware of the shortcomings, you might get away with it, though. Try
Pattern titleFinder = Pattern.compile("<a[^>]*>(.*?)</a>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher regexMatcher = titleFinder.matcher(subjectString);
while (regexMatcher.find()) {
// matched text: regexMatcher.group(1)
}
will iterate over all matches in a string.
It won't handle nested <a> tags and ignores all the attributes inside the tag.
str.replaceAll("</?a>", "");
Here is online ideone demo
Here is similar topic : How to remove the tags only from a text ?