I want search a div for a string like "12345" and then put every matched string into a span.
But when find repetitive string, just do it for first matched several time.
Here is a jsfiddle:
function find(){
var regex = new RegExp(/12345/g),
list = $(".test").html().match(regex);
console.log(list)
for(each in list){
replacement = $(".test").html().replace(list[each], "<span class='box'>"+list[each]+"</span>");
$(".test").html(replacement);
}
}
find();
.box{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<p>
12345 12345
</p>
</div>
Your approach is faulty: rather than extracting all matching substrings and later iterate them performing single replacements, you may use your own regex inside a String#replace method to modify the substrings "inline", "on-the-match" way:
function find(){
var regex = /12345/g;
var replacement = $(".test").html().replace(regex, "<span class='box'>$&</span>");
$(".test").html(replacement);
}
find();
.box{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">
<p>
12345 12345
</p>
</div>
My solution (fiddle here), with pure JavaScript :
function find(){
var motif = "12345"
var regex = new RegExp(motif, "g")
document.querySelector("div.test").innerHTML = document.querySelector("div.test").innerHTML.replace(regex, "<span class='box'>" + motif + "</span>")
}
find()
Related
I want to extract email address from the Html String. First I extract the text from html string then pass the returning string into regular expression to search for email address.
import 'package:html/parser.dart';
import 'package:flutter/material.dart';
String _parseString(String htmlString) {
var document = parse(htmlString);
String parsedString = parse(document.body.text).documentElement.text;
return parsedString;
}
String _parseEmailString(String htmlString) {
var document = parse(htmlString);
String parsedString = parse(document.body.text).documentElement.text;
RegExp exp = new RegExp(
r"^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$",
caseSensitive: false,
multiLine: false,
);
Iterable<RegExpMatch> matches = exp.allMatches('WS://127.0.0.1:56789');
print("hasMatch : " + exp.firstMatch("shahryar.rsm#gmail.com").toString());
var matches2 = "hasMatch : " + exp.stringMatch(parsedString).toString();
return matches2;
}
class HtmlToText extends StatelessWidget {
#override
Widget build(BuildContext context) {
String string =
'<p style=\"text-align: center\"><strong>The CV Club</strong> is a professional writing service that specialise in tailoring CVs, cover letters and more to your desired industry/ job role.</p>\n<p style=\"text-align: center\">The internet is full of dull CV templates, all exactly the same as each other. That’s why at <strong>The CV Club</strong>, we professionally tailor your CV to be as individual as you are and not at extortionate prices!</p>\n<p style=\"text-align: center\">We offer a FREE CV review and will give you constructive feedback on your current CV!</p>\n<p>Contact us on;</p>\n<p><strong>Website: https://www.thecvclub.org/</strong></p>\n<p><strong>Email: thecvclub#gmail.com</strong></p>\n<p><strong>Twitter: thecvclub_</strong></p>\n<p><img data-attachment-id=\"1055\" data-permalink=\"https://soleentrepreneur.co.uk/happy-world-book-day/\" data-orig-file=\"https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?fit=800%2C800&ssl=1\" data-orig-size=\"800,800\" data-comments-opened=\"1\" data-image-meta=\"{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}\" data-image-title=\"Happy World Book Day!\" data-image-description=\"\" data-medium-file=\"https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?fit=300%2C300&ssl=1\" data-large-file=\"https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?fit=800%2C800&ssl=1\" class=\"alignnone size-medium wp-image-1055 alignleft\" src=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day-300x300.png?resize=300%2C300\" alt=\"\" width=\"300\" height=\"300\" srcset=\"https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=300%2C300&ssl=1 300w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=80%2C80&ssl=1 80w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=768%2C768&ssl=1 768w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=36%2C36&ssl=1 36w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=180%2C180&ssl=1 180w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=705%2C705&ssl=1 705w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=120%2C120&ssl=1 120w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=450%2C450&ssl=1 450w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=640%2C640&ssl=1 640w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?resize=50%2C50&ssl=1 50w, https://i2.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Happy-World-Book-Day.png?w=800&ssl=1 800w\" sizes=\"(max-width: 300px) 100vw, 300px\" data-recalc-dims=\"1\" /> <img data-attachment-id=\"1056\" data-permalink=\"https://soleentrepreneur.co.uk/lets-celebrate/\" data-orig-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?fit=800%2C800&ssl=1\" data-orig-size=\"800,800\" data-comments-opened=\"1\" data-image-meta=\"{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}\" data-image-title=\"Let’s celebrate\" data-image-description=\"\" data-medium-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?fit=300%2C300&ssl=1\" data-large-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?fit=800%2C800&ssl=1\" class=\"alignnone size-medium wp-image-1056 alignleft\" src=\"https://i0.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate-300x300.png?resize=300%2C300\" alt=\"\" width=\"300\" height=\"300\" srcset=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=300%2C300&ssl=1 300w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=80%2C80&ssl=1 80w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=768%2C768&ssl=1 768w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=36%2C36&ssl=1 36w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=180%2C180&ssl=1 180w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=705%2C705&ssl=1 705w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=120%2C120&ssl=1 120w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=450%2C450&ssl=1 450w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=640%2C640&ssl=1 640w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?resize=50%2C50&ssl=1 50w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Lets-celebrate.png?w=800&ssl=1 800w\" sizes=\"(max-width: 300px) 100vw, 300px\" data-recalc-dims=\"1\" /> <img data-attachment-id=\"1059\" data-permalink=\"https://soleentrepreneur.co.uk/need-help-with-your-cv_/\" data-orig-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?fit=800%2C800&ssl=1\" data-orig-size=\"800,800\" data-comments-opened=\"1\" data-image-meta=\"{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}\" data-image-title=\"Need help with your CV_\" data-image-description=\"\" data-medium-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?fit=300%2C300&ssl=1\" data-large-file=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?fit=800%2C800&ssl=1\" class=\"alignnone size-medium wp-image-1059 alignleft\" src=\"https://i0.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_-300x300.png?resize=300%2C300\" alt=\"\" width=\"300\" height=\"300\" srcset=\"https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=300%2C300&ssl=1 300w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=80%2C80&ssl=1 80w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=768%2C768&ssl=1 768w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=36%2C36&ssl=1 36w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=180%2C180&ssl=1 180w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=705%2C705&ssl=1 705w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=120%2C120&ssl=1 120w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=450%2C450&ssl=1 450w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=640%2C640&ssl=1 640w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?resize=50%2C50&ssl=1 50w, https://i1.wp.com/soleentrepreneur.co.uk/wp-content/uploads/2019/02/Need-help-with-your-CV_.png?w=800&ssl=1 800w\" sizes=\"(max-width: 300px) 100vw, 300px\" data-recalc-dims=\"1\" /></p>\n<p> </p>\n';
return Scaffold(
appBar: AppBar(),
body: Column(children: <Widget>[
SelectableText(
_parseString('$string'),
),
Text(_parseEmailString('$string'))
]));
}
}
Found out using wrong regex Regular Expression was
r"[a-zA-Z0-9-_.]+#[a-zA-Z0-9-_.]+"
In my app, I'm trying to split a string into an array based on a regex pattern. I'd like to be able to load my volt templates and run them through our custom rendering engine - just to learn a bit more on how rendering engines work.
I wrote the regex below to do just that:
"(?s)(\\{\\{.*?\\}\\}|\\{%.*?%\\}|\\{#.*?#\\})"
And this is an example of such a template:
# {{ title }}
{{created_at}} {{created_location}}
============
Paragraphs are separated by a blank line.
2nd paragraph. *Italic*, **bold**, and `monospace`.
Itemized lists look like:
{% for (item in items) %}
* {{ item }}
{% endfor %}
Now, ideally, I'd like this to be converted to an array looking like this:
[
"# ",
"{{ title }}",
"\n",
"{{created_at}}",
" ",
"{{created_location}}",
"\n============\nParagraphs are separated by a blank line\n2nd paragraph. *Italic*, **bold**, and `monospace`.\n\nItemized lists look like:"
"{% for (item in items) %}",
"\n* {{ item }}\n",
"{% endfor %}"
]
However, when I run the regex above, I get:
[
"Paragraphs are separated by a blank line.\n2nd paragraph. *Italic*, **bold**, and `monospace`.\n\nItemized lists look like:",
"{% for (item in items) %}\n* {{ item }}",
"{% endfor %}\n"
]
As you can see the title part completely disappears. Furthermore, there seem to be some issues with the newline characters. Any ideas how I could solve this?
The problem wasn't in the regex, but in the code that I was using to split on the regex. I modified the code below to also return the regex itself.
extension NSRegularExpression {
func split(_ str: String) -> [String] {
let range = NSRange(location: 0, length: str.characters.count)
//get locations of matches
var matchingRanges: [NSRange] = []
let matches: [NSTextCheckingResult] = self.matches(in: str, options: [], range: range)
for match: NSTextCheckingResult in matches {
matchingRanges.append(match.range)
}
//invert ranges - get ranges of non-matched pieces
var pieceRanges: [NSRange] = []
//add first range
pieceRanges.append(NSRange(location: 0, length: (matchingRanges.count == 0 ? str.characters.count : matchingRanges[0].location)))
var endLoc: Int = 0
var startLoc: Int = 0
//add between splits ranges and last range
for i in 0..<matchingRanges.count {
let isLast = i + 1 == matchingRanges.count
let location = matchingRanges[i].location
let length = matchingRanges[i].length
startLoc = location + length
endLoc = isLast ? str.characters.count : matchingRanges[i + 1].location
pieceRanges.append(NSRange(location: startLoc, length: endLoc - startLoc))
}
var pieces: [String] = []
var previous: NSRange = NSRange(location: 0, length: 0)
for range: NSRange in pieceRanges {
let item = (str as NSString).substring(with: NSRange(location:previous.location+previous.length, length:range.location-(previous.location+previous.length)))
pieces.append(item)
let piece = (str as NSString).substring(with: range)
pieces.append(piece)
previous = range
}
return pieces
}
}
I have a problem when using Regex. I have a html document which create an anchor link when it matches condition.
An example html:
Căn cứ Luật Tổ chức HĐND và UBND ngày 26/11/2003;
Căn cứ Nghị định số 63/2010/NĐ-CP ngày 08/6/2010 của Chính phủ về
kiểm soát thủ tục hành chính;
Căn cứ Quyết định số 165/2011/QĐ-UBND ngày 06/5/2011 của UBND tỉnh
ban hành Quy định kiểm soát thủ tục hành chính trên địa bàn tỉnh;
Căn cứ Quyết định số 278/2011/QĐ-UBND ngày 02/8/2011 của UBND tỉnh
ban hành Quy chế phối hợp thực hiện thống kê, công bố, công khai thủ
tục hành chính và tiếp nhận, xử lý phản ánh, kiến nghị của cá nhân, tổ
chức về quy định hành chính trên địa bàn tỉnh;
Xét đề nghị của Giám đốc Sở Công Thương tại Tờ trình số
304/TTr-SCT ngày 29 tháng 5 năm 2013
I want to match these bold texts and make anchor links from these. If it has, try ignore. Link example 63/2010/NĐ-CP
var matchLegals = new Regex(#"(?:[\d]+\/?)\d+\/[a-z\dA-Z_ÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠàáâãèéêìíòóôõùúăđĩũơƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂưăạảấầẩẫậắằẳẵặẹẻẽềềểỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰỲỴÝỶỸửữựỳỵỷỹ\-]+", RegexOptions.Compiled);
var doc = new HtmlDocument();
doc.LoadHtml(htmlString);
var allElements = doc.DocumentNode.SelectSingleNode("//div[#class='main-content']").Descendants();
foreach (var node in allElements)
{
var matches = matchLegals.Matches(node.InnerHtml);
foreach (Match m in matches)
{
var k = m.Value;
//dont know what to do
}
}
What can i do this
Many thanks.
I assume your regex pattern is OK and works. Another assumption is that node.InnerHtml doesn't contain any <a> tags already encompassing any of the potential matches.
In this case, it's as simple as doing something like this:
node.InnerHtml = Regex.Replace(node.InnerHtml, "[your pattern here]", "<a href='query=$&'>$&</a>");
...
doc.Save("output.html");
Note, that you may need to work on the href component - I'm unsure how your link should be built.
you match text and replace:
<script>
var s = '...';
var matchs = s.match(/\d{2,3}\/\d{4}\/[a-zA-Z\-áàảãạăâắằấầặẵẫậéèẻẽẹêếềểễệóòỏõọôốồổỗộơớờởỡợíìỉĩịđùúủũụưứửữựÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼÊỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỨỪỬỮỰỲỴÝỶỸửữựỵỷỹ]+/gi);
if (matchs != null) {
for(var i=0; i<matchs.length;i++){
var val = matchs[i];
s = s.replace(val, '<a href="?key=' + val + '"/>' + val + '</a>');
}
}
document.write(s);
</script>
#Shaamaan thank for your advice. After few hours of coding, it works now
var content = doc.DocumentNode.SelectSingleNode("//div[#class='main-content']");
var items = content.SelectNodes(".//text()[normalize-space(.) != '']");
foreach (HtmlNode node in items)
{
if (!matchLegals.IsMatch(node.InnerText) || node.ParentNode.Name == "a")
{
continue;
}
var texts = node.InnerHtml.Trim();
node.InnerHtml = matchLegals.Replace(texts, a => string.Format("<a href='/search?q={0}'>{0}</a>",a.Value));
}
I'm trying to filter strings in a static unordered list. I'm able to filter items in an array but not sure how to do it for static html content.
The way I've learned to achieve it using an array is by using this method:
<input type="search" ng-model="name" />
<ul>
<li ng-repeat="person in people | filter:name">
{{ person }}
</li>
</ul>
I'm trying to achieve the same effect using an existing <ul>
<input type="search" ng-model="filter.name" placeholder="filter..." />
<ul>
<li>Bob/li>
<li>Lisa</li>
<li>Lewis</li>
<li>Xuemin</li>
<li>Tom</li>
<li>Cassidy</li>
</ul>
I want to be able to filter the list items based on the text strings inside them, so for example typing 'L' in the textbox would only show:
Lisa
Lewis
Here is a hacked out way of doing it JSFiddle.
The key to it is in ng-change="filter()". Every time you enter a letter you decide which elements to show or hide.
$scope.filter = function() {
var elem = document.getElementById('list');
for (var i = 0; i < elem.children.length; i++) {
var name = elem.children[i].children[0].innerHTML;
if (name.indexOf($scope.name) != -1 || $scope.name == "") {
elem.children[i].style.display = "block";
} else {
elem.children[i].style.display = "none";
}
}
}
Like I said, it's an ugly hack, but it works. You would be better off making an object out of your names, and using ng-repeat.
any ideas??
I have this code in hundreds of pages I need to remove it from all these pages but because of the " var s " where everypage is a different 4 digit number i cant just do a find and replace replace with nothing
.
How can I create a powershell command using regex on those four digits.
<script language="javascript" type="text/javascript">
var d = '<%=joindomain%>';
var s = '9244';
var a = '<%=Request.QueryString("aff") %>';
var c = '<%=Request.QueryString("camp") %>';
var r = '<%=referer %>';
</script>
Thank you
Rico
Not sure how general you can be here... Code below may do more than you ask for, if that is the case - just add more things to disambiguate it. Anyway, it did the job for me... ;)
#'
foo
<script language="javascript" type="text/javascript">
var d = '<%=joindomain%>';
var s = '9244';
var a = '<%=Request.QueryString("aff") %>';
var c = '<%=Request.QueryString("camp") %>';
var r = '<%=referer %>';
</script>
bar
'# -replace '<script language[\s\S]*?var s = ''\d{4}''[\s\S]*?</script>'
it will remove any piece of text between "" that contains string "var s = '####'" (4 digits). Notice that I would have to escape things for regex and single quotes for it to work. At some point you may consider [Regex]::Escape method handy, if you want to be very specific...