Removing tabs and newlines with regular expressions issue - regex

Regex: remove TAB \t tab var regex = /\s[A-Za-z]+/g do not work
selectFirstEmptyRow function () {
var ss = SpreadsheetApp.openByUrl ("https://docs.google.com/spreadsheets/d/---ID-----edit#gid=395019283");
var date = Utilities.formatDate(new Date() ss.getSpreadsheetTimeZone(), "d" + "- 0" + "M" + "-" + "y");
var sheet = ss.getSheetByName(date);
var regex = /[^0-9]*/g; // extract the string before digital channel
var doc = DocumentApp.getActiveDocument().getText()
var result = RegExp.exec(doc);
// * Extract white \ s match any white space character [\ r \ n \ t \ f]
var regex = /\s[A-Za-z]+/g; // extract the spaces in front of and behind "Name Surname"
RegExp.exec var result = (result);
sheet.setActiveSelection(sheet getRange ("B" + getFirstEmptyRowWholeRow())).setValue(result);
Logger.log(result.getText);
I can not remove a tab \t and newlines \n with the syntax
var regex = /\s[A-Za-z]+/g;
There remains a line preceding the string "Name Surname" when I insert it into the Spreadsheet.
After analysis it appears that the concerns are the tabs \t, it is not deleted.
I try to extract from a "text document" a string (which is always at the top of the document until the first numerical chain) and put in a "spreadsheet document 'Spreadsheet at the site of the first box vacuum column "B".
The handling of this string in the same "text document" did not cause me any problem for the update of age with the syntax
var regex = /[^0-9]*/g; // extract the string before a digit
The string from the document:
var str = '\n\n\n\Surname NAME\n34 Years\n\n......... .. "
Here is the complete script:
/// var result = result.replace(/^[\r\n]+|.|[\r\n]+$/g, "");// extrait les espaces devant et derriere Nom Prenom GAS D'ONT WORK
///// Facturer Acte ////
function FacturerActe() {
var regexp = /[^0-9]*/g ;// extrait la chaine de caractère avant la chaine numérique
var doc = DocumentApp.getActiveDocument().getText();
var result = regexp.exec(doc);
var PrenomNom = new RegExp(result,"gm");
Logger.log(PrenomNom.getText);
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gj6peXR3hjvj51FxDFt2gFkU/edit#gid=395019283");
var date = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone() , "d"+"-"+"mm"+"-"+"y");
var sheet = ss.getSheetByName(date);
ss.setActiveSheet(sheet);
var cell = sheet.getRange("A40");
cell.setNote("Aujourd'hui est un nouveau jour ! Nous sommes le :"+date);
selectFirstEmptyRow(); // Place le curseur sur la premiere ligne Vide de la Colonne "B"
}
//* Placez le curseur de l'utilisateur actuel dans la première cellule de la première ligne vide.
//*
function selectFirstEmptyRow() {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gj6peXR3hjvj51FxDFt2gFkU/edit#gid=395019283");
var date = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone() , "d"+"-"+"mm"+"-"+"y");
var sheet = ss.getSheetByName(date);
var regexp = /[^0-9]*/g ;// extrait la chaine de caractère avant la chaine numérique
var doc = DocumentApp.getActiveDocument().getText();
var result = regexp.exec(doc);
var regexp = /\s[A-Z a-z]+/g ;// extrait les espaces devant et derriere Nom Prenom
//* Extrait les blancs
var result = regexp.exec(result);
/// var result = result.replace(/^[\r\n]+|\.|[\r\n]+$/g, "");// extrait les espaces devant et derriere Nom Prenom GAS D'ONT WORK
sheet . setActiveSelection (sheet.getRange("B" + getFirstEmptyRowWholeRow())).setValue(result);
Logger.log(result.getText);
}
/**
* " Trouve la première ligne vide la Colonne "B" " de checker de Mogsdad.
*/
function getFirstEmptyRowWholeRow () {
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/19rWt8JEGbYM29-W4tI2gj6peXR3hjvj51FxDFt2gFkU/edit#gid=395019283");
var date = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone(), "d"+"-"+"mm"+"-"+"y");
var sheet = ss.getSheetByName(date);
var range = sheet.getDataRange();
var values = range.getValues();
var row = 1 ;
for (var row = 1; row < values.length; row ++) {
if (!values[ row ].join("")) break ;
}
return (row + 1);
}
///// Fin Facturer Acte ////

As per Using regular expressions to search for data in your spreadsheet, you can match any newline and tab using [\t\r\n] pattern. Since you have more than one at a stretch, you should add a quantificator +. Also, since you are looking to capture 2 lines, you should add the [\t\r\n]+ to the pattern, too.
This will let you capture the 2 lines with Name and Age in between the newlines:
[\r\n\t]+(.+[\r\n\t]+.+)[\t\r\n]+
And you can later remove the newline characters:
var result = str.replace(/[\r\n\t]+(.+[\r\n\t]+.+)[\t\r\n]+/, '$1');
Here is what it looks like on regex101.com.
alert("'" + "\n\t\n\nNew line\n\t\nSecond 34 line\n\t\n....".replace(/[\r\n\t]+(.+[\r\n\t]+.+)[\t\r\n]+/, '$1') + "'")

Related

Find and change cyrillic word with boundary in google scripts

The problem is that \b doesn't work with Russian and Ukrainian letters.
Here I try to find all matches of a word 'февраля' it the text, change them to tempword, then make it a link and change it back to 'февраля'.
function addLinks(word, siteurl) {
var id = 'doc\'s ID';
var doc = DocumentApp.openById(id);
var body = doc.getBody();
var tempword = 'ASDFDSGDDKDSL2';
var searchText = "\\b"+word+"\\b";
var element = body.findText(searchText);
console.log(element);
while (element) {
var start = element.getStartOffset();
var text = element.getElement().asText();
text.replaceText(searchText, tempword);
text.setLinkUrl(start, start + tempword.length - 1, siteurl);
element = body.findText(searchText);
}
body.replaceText(tempword, word);
}
addLinks('февраля', 'example.com');
It works as it should, if I change Russian word 'февраля' to English 'february'.
addLinks('february', 'example.com');
I need regular expression, because if I just look for 'февраля' script will apply it to other words like 'февралям', 'февралями' etc.
So, it is a question, how to make it work.
Mistake "Exception: Invalid regular expression pattern" occurs with this code:
var searchText = "(?<=[\\s,.:;\"']|^)"+word+"(?=[\\s,.:;\"']|$)";
or this:
var searchText = "(^|\s)"+word+"(?=\s|$)";
and some other.
Here is my solution:
function main() {
addLinks('февраля', 'example.com');
}
function addLinks(word, url) {
var doc = DocumentApp.getActiveDocument();
var pgfs = doc.getParagraphs();
var bound = '[^А-яЁё]'; // any letter except Russian one
var patterns = [
{regex: bound + word + bound, start: 1, end: 1}, // word inside of line
{regex: '^' + word + bound, start: 0, end: 1}, // word at the start
{regex: bound + word + '$', start: 1, end: 0}, // word at the end
{regex: '^' + word + '$', start: 0, end: 0} // word = line
];
for (var pgf of pgfs) for (var pattern of patterns) {
var location = pgf.findText(pattern.regex);
while (location) {
var start = location.getStartOffset() + pattern.start;
var end = location.getEndOffsetInclusive() - pattern.end;
pgf.editAsText().setLinkUrl(start, end, url);
location = pgf.findText(pattern.regex, location);
}
}
}
Test output:
It handles well the word placed at the start or at the end of the line (or both). And it gives no the weird error message.

onEdit runs only half of the script

I need to use a script that sends data from one sheet to a different one and to clear the values after writing on a specific cell.
I've tried onEdit and it clears the values but doesn't insert them in the second sheet. This is the code I have so far:
function onEdit(e) {
if (e.range.getA1Notation() == "F6"){
//Copiar los datos originales
var ss1 = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss1.getSheetByName("Hoja 1");
var A = sheet1.getRange("B5").getValues();
var B = sheet1.getRange("F5").getValues();
var C = sheet1.getRange("A8:F22").getValues();
//Borrar valores de la hoja de origen después de copiar
var borrar = sheet1.getRange("B5").clearContent();
var borrar = sheet1.getRange("F6").clearContent();
var borrar = sheet1.getRange("A8:F22").clearContent();
//Spreadsheet en la que voy a copiar lo anterior
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1zF84h_gR0zHPqwobYyuOQlo50L2ktpZr2e4orMNtqE8/edit#gid=382646794');
var sheet = ss.getSheetByName("PEDIDOS SIN ORDENAR");
var lastRow = sheet.getLastRow() + 1;
//Insertar los valores
var destRange = sheet.getRange(lastRow, 1, A.length, A[0].length).setValues(A);
var destRange = sheet.getRange(lastRow, 2, B.length, B[0].length).setValues(B);
var destRange = sheet.getRange(lastRow, 3, C.length, C[0].length).setValues(C);
}}
If I change the name of the code and don't condition it to the content of cell F6, then the code runs completely. For that reason I tried to use a button, which works perfetly fine in PC but I need it to work also in mobile devices and buttons don't work with Android.
My last try was:
function Enviar() {
//if (e.range.getA1Notation() == "F6"){
//Copiar los datos originales
var ss1 = SpreadsheetApp.getActiveSpreadsheet();
var sheet1 = ss1.getSheetByName("Hoja 1");
var A = sheet1.getRange("B5").getValues();
var B = sheet1.getRange("F5").getValues();
var C = sheet1.getRange("A8:F22").getValues();
//Borrar valores de la hoja de origen después de copiar
var borrar = sheet1.getRange("B5").clearContent();
var borrar = sheet1.getRange("F6").clearContent();
var borrar = sheet1.getRange("A8:F22").clearContent();
var D = sheet1.getRange("F6").getValues()
if (D == "SI"){
//Spreadsheet en la que voy a copiar lo anterior
var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1zF84h_gR0zHPqwobYyuOQlo50L2ktpZr2e4orMNtqE8/edit#gid=382646794');
var sheet = ss.getSheetByName("PEDIDOS SIN ORDENAR");
var lastRow = sheet.getLastRow() + 1;
//Insertar los valores
var destRange = sheet.getRange(lastRow, 1, A.length, A[0].length).setValues(A);
var destRange = sheet.getRange(lastRow, 2, B.length, B[0].length).setValues(B);
var destRange = sheet.getRange(lastRow, 3, C.length, C[0].length).setValues(C);
}}
This last try doesn't seem to do anything at all.
None of my tries shows error, the script runs but doesn't give the expected results.
I don't know what else I could do. Please I need some help.
function Enviar(e) {
//Currently this function runs for any edit of any sheet you should consider limiting it to only the sheet and cell range that you desire
var ss1=SpreadsheetApp.getActiveSpreadsheet();
var sh1=e.source.getSheetByName("Hoja 1");
var A=sh1.getRange("B5").getValue();//single value
var B=sh1.getRange("F5").getValue();//single value
var C=sh1.getRange("A8:F22").getValues();//2D array
var borrar=sh1.getRange("B5").clearContent();
var borrar=sh1.getRange("F6").clearContent();
var borrar=sh1.getRange("A8:F22").clearContent();
var D=sh1.getRange("F6").getValue()
if (D=="SI"){
var ss=SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1zF84h_gR0zHPqwobYyuOQlo50L2ktpZr2e4orMNtqE8/edit#gid=382646794');
var sh=ss.getSheetByName("PEDIDOS SIN ORDENAR");
var lastRow=sh.getLastRow() + 1;
var destRange=sh.getRange(lastRow,1).setValue(A);//single value
var destRange=sh.getRange(lastRow,2).setValue(B);//single value
var destRange=sh.getRange(lastRow, 3,C.length,C[0].length).setValues(C);//2D array
}
}

How to use a regex to extract a URL from a JavaScript function?

I tried to learn regex to do this simple task, I tested may patterns using regex101.com editor but with no success.
I want to extract this link (http://mp3lg4.tdf-cdn.com/9243/lag_164753.mp3) from this javascript text, please note that the links doesn't always end with mp3, it could end with anything.
JavaScript Text:
function reqListener () {
var div = document.createElement("div");
div.innerHTML = new XMLSerializer().serializeToString(this.responseXML.documentElement);
document.body.insertBefore(div, document.body.childNodes[0]);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "//static.radio.fr/inc/v2/images/icons/icon-sprites.svg?_=93cbcb9ebf4e2d5276480a0d9c06c653056f0d85");
oReq.send();
var environment = {
develop: false,
production: true,
debug: false
};
if (window.environment && window.environment.production) {
window.console.debug = function() {};
window.console.log = function() {};
}
var require = {
baseUrl: "/inc/v2/js",
config: {
'logger': {
enabled: false,
filter: (window.environment && window.environment.develop) && (window.location.search.indexOf('test_production=') === -1) ? 'debug' : 'info'
},
'components/station/stationService': {
station: {"continent":"Europe","country":"France","logo300x300":"http://static.radio.fr/images/broadcasts/15/43/8275/1/c300.png","city":"Paris","stationType":"radio_station","description":"Virgin Radio est une station de radio musicale privée Française. Elle a été créée en 2008, suite au changement de nom de la radio Europe 2, et fait partie du groupe Lagardère SCA. La radio cible une audience de jeunes adultes grâce aux hits Electro-Rock et Pop qu’elle propose. L’audience de la chaîne dépasse les 2,7 millions d’auditeurs quotidiens.\r\nCette radio FM est disponible dorénavant par internet grâce à ses flux de diffusion MP3 de 64 et 128 kbps.\r\nAprès son passage à vide du début des années 2010, Virgin Radio revient en force avec son son “Pop - Rock - Electro”.","language":["Français"],"logo100x100":"http://static.radio.fr/images/broadcasts/15/43/8275/1/c100.png","streamUrls":[{"streamUrl":"http://mp3lg4.tdf-cdn.com/9243/lag_164753.mp3","loadbalanced":false,"metaDataAvailable":false,"playingMode":"STEREO","type":"STREAM","sampleRate":44100,"streamContentFormat":"MP3","bitRate":128,"idBroadcast":8275,"sortOrder":0,"streamFormat":"ICECAST","id":47609,"streamStatus":"VALID","contentType":"audio/mpeg"},{"streamUrl":"http://mp3lg3.scdn.arkena.com/10490/virginradio.mp3","loadbalanced":false,"metaDataAvailable":false,"playingMode":"STEREO","type":"STREAM","sampleRate":44100,"streamContentFormat":"MP3","bitRate":64,"idBroadcast":8275,"sortOrder":1,"streamFormat":"ICECAST","id":57003,"streamStatus":"VALID","contentType":"audio/mpeg"}],"playable":"PLAYABLE","genres":["Pop","Rock"],"logo175x175":"http://static.radio.fr/images/broadcasts/15/43/8275/1/c175.png","adParams":{"st_city":["Paris"],"languages":["Français"],"genres":["Pop","Rock"],"topics":[],"st_cont":["Europe"],"station":["virginradio"],"family":["Virgin"],"st_region":[],"type":["radio_station"],"st_country":["France"]},"alias":"Virgin;;Virgin Radio;;103.5;;103,5;Pop Rock Electro","rank":8,"id":8275,"types":["Radio FM"],"website":"http://www.virginradio.fr/","topics":[],"shortDescription":"Virgin Radio propose d'écouter le meilleur des sons “Pop - Rock - Electro”","logo44x44":"http://static.radio.fr/images/broadcasts/15/43/8275/1/c44.png","numberEpisodes":0,"podcastUrls":[],"hideReferer":false,"name":"Virgin Radio Officiel","subdomain":"virginradio","lastModified":"2018-05-10T03:18:17.000Z","family":["Virgin"],"region":"","frequencies":[{"area":"Abbeville","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":2299,"frequency":99.6},{"area":"Agen","broadcastId":8275,"frequencyType":"FM","cityId":4416,"id":2317,"frequency":89.8},{"area":"Ajaccio","broadcastId":8275,"frequencyType":"FM","cityId":165,"id":2370,"frequency":99.8},{"area":"Alençon","broadcastId":8275,"frequencyType":"FM","cityId":2956,"id":2424,"frequency":100.9},{"area":"Allos","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":2465,"frequency":105.4},{"area":"Amiens","broadcastId":8275,"frequencyType":"FM","cityId":185,"id":2502,"frequency":93.6},{"area":"Angers","broadcastId":8275,"frequencyType":"FM","cityId":193,"id":2542,"frequency":94.8},{"area":"Angoulême","broadcastId":8275,"frequencyType":"FM","cityId":1975,"id":2564,"frequency":100.3},{"area":"Annecy","broadcastId":8275,"frequencyType":"FM","cityId":198,"id":2587,"frequency":100.5},{"area":"Annemasse","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":2594,"frequency":90.1},{"area":"Arcachon","broadcastId":8275,"frequencyType":"FM","cityId":5789,"id":2644,"frequency":94.1},{"area":"Argentan","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":2668,"frequency":96.1},{"area":"Arras","broadcastId":8275,"frequencyType":"FM","cityId":2721,"id":2708,"frequency":91.9},{"area":"Aubenas","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":2759,"frequency":106.9},{"area":"Aubusson","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":2783,"frequency":101.8},{"area":"Auch","broadcastId":8275,"frequencyType":"FM","cityId":230,"id":2799,"frequency":100.2},{"area":"Aurillac","broadcastId":8275,"frequencyType":"FM","cityId":237,"id":2845,"frequency":89},{"area":"Autun","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":2861,"frequency":87.6},{"area":"Auxerre","broadcastId":8275,"frequencyType":"FM","cityId":240,"id":2881,"frequency":98.9},{"area":"Avallon","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":2904,"frequency":90.8},{"area":"Avignon","broadcastId":8275,"frequencyType":"FM","cityId":241,"id":2927,"frequency":89},{"area":"Avranches","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":2938,"frequency":89},{"area":"Bar-le-Duc","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3007,"frequency":102},{"area":"Barcelonnette","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3027,"frequency":94},{"area":"Bastia","broadcastId":8275,"frequencyType":"FM","cityId":1962,"id":3066,"frequency":107.2},{"area":"Bayeux","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3078,"frequency":101.7},{"area":"Bayonne","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3095,"frequency":97.7},{"area":"Beauvais","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3129,"frequency":103.5},{"area":"Belfort","broadcastId":8275,"frequencyType":"FM","cityId":303,"id":3163,"frequency":98.4},{"area":"Bellegarde-sur-Valserine","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3186,"frequency":103.1},{"area":"Belley","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3199,"frequency":96.1},{"area":"Bergerac","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3217,"frequency":93.2},{"area":"Besançon","broadcastId":8275,"frequencyType":"FM","cityId":324,"id":3261,"frequency":100.4},{"area":"Béthune","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3276,"frequency":90.1},{"area":"Blois","broadcastId":8275,"frequencyType":"FM","cityId":344,"id":3325,"frequency":97.2},{"area":"Bonnières-sur-Seine","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3358,"frequency":88.8},{"area":"Bordeaux","broadcastId":8275,"frequencyType":"FM","cityId":360,"id":3387,"frequency":94.3},{"area":"Boulogne-sur-Mer","broadcastId":8275,"frequencyType":"FM","cityId":365,"id":3419,"frequency":91.5},{"area":"Bourg-en-Bresse","broadcastId":8275,"frequencyType":"FM","cityId":1991,"id":3442,"frequency":96.3},{"area":"Bourges","broadcastId":8275,"frequencyType":"FM","cityId":366,"id":3475,"frequency":99.6},{"area":"Brest","broadcastId":8275,"frequencyType":"FM","cityId":379,"id":3526,"frequency":96.5},{"area":"Briançon","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3554,"frequency":96},{"area":"Brioude","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3577,"frequency":89.8},{"area":"Brive-la-Gaillarde","broadcastId":8275,"frequencyType":"FM","cityId":1996,"id":3600,"frequency":88.1},{"area":"Caen","broadcastId":8275,"frequencyType":"FM","cityId":413,"id":3628,"frequency":96.8},{"area":"Cahors","broadcastId":8275,"frequencyType":"FM","cityId":10713,"id":3647,"frequency":96.8},{"area":"Calvi","broadcastId":8275,"frequencyType":"FM","cityId":10711,"id":3686,"frequency":106.7},{"area":"Cannes","broadcastId":8275,"frequencyType":"FM","cityId":423,"id":3717,"frequency":88.1},{"area":"Carcassonne","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3753,"frequency":96},{"area":"Carhaix-Plouguer","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3756,"frequency":106.8},{"area":"Carpentras","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3766,"frequency":103.3},{"area":"Castelnaudary","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3789,"frequency":102.3},{"area":"Castres","broadcastId":8275,"frequencyType":"FM","cityId":440,"id":3804,"frequency":102.4},{"area":"Cauterets","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3810,"frequency":94.1},{"area":"Chalon-sur-Saône","broadcastId":8275,"frequencyType":"FM","cityId":8551,"id":3872,"frequency":97.8},{"area":"Châlons-en-Champagne","broadcastId":8275,"frequencyType":"FM","cityId":11051,"id":3893,"frequency":95.5},{"area":"Chamonix","broadcastId":8275,"frequencyType":"FM","cityId":1986,"id":3939,"frequency":98.3},{"area":"Charleville-Mézières","broadcastId":8275,"frequencyType":"FM","cityId":459,"id":3962,"frequency":99.9},{"area":"Charolles","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3969,"frequency":95.1},{"area":"Chartres","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":3987,"frequency":103.3},{"area":"Château-du-Loir","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":4002,"frequency":103.7},{"area":"Château-Thierry","broadcastId":8275,"frequencyType":"FM","cityId":0,"id":4021,"frequency":102.4},{"area":"Châteaubriant","broadcastId":8275,"frequencyType":"FM","cityId":6200,"id":4030,"frequency":88.6},{"area":"…
I want to apply this regex pattern in this code:
Public Function regExInput(myPatern As String, myInput As String) As String
Dim strPattern As String: strPattern = myPatern
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
regExInput = myInput
If strPattern <> "" Then
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(regExInput) Then
MsgBox (regEx.Replace(regExInput, strReplace))
Else
MsgBox ("Not matched")
End If
End If
End Function
Here is a regex that should do what you want:
/{\s*["']\s*streamUrl\s*["']\s*:\s*["']\s*(http[^"']+)/
Try it out here:
https://regex101.com/r/sAXaOE/1
The match is in Group 1 (look under match info on the right).
And in VBA it might be something like this:
Dim myRegExp, myMatches, myMatch
Set myRegExp = New RegExp
myRegExp.IgnoreCase = True
myRegExp.Global = True
myRegExp.Pattern = "{\s*[""']\s*streamUrl\s*[""']\s*:\s*[""']\s*(http[^""']+)"
Set myMatches = myRegExp.Execute(SubjectString)
For Each myMatch In myMatches
For I = 1 To myMatch.SubMatches.Count
'backreference text: myMatch.SubMatches(I-1)
Next
Next

Replacement matching regex with anchor tag?

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));
}

Facebook api can't see my scheduled photo post

My code get a list of image from directory and schedule it for publishing on my page.
Scheduling works: when i'm logged in as page admin, i can see scheduled post. But i can't see them loggin in with another account (which isn't admin)...What's wrong?
I've tried to use both
$photo_details['published'] = "0";
and
$photo_details['published'] = FALSE;
and
$photo_details['published'] = TRUE;
But nothing changed...
Thanks!
$page_info = $facebook->api("/$pageId?fields=access_token");
echo "<br>TOKEN=".$page_info['access_token'];
$facebook->setFileUploadSupport(true);
//Create an album
$album_details = array(
'message'=> 'Album desc',
'name'=> 'Album name',
'access_token' => $page_info['access_token']
);
$create_album = $facebook->api('/me/albums', 'post', $album_details);
//Get album ID of the album you've just created
$album_uid = $create_album['id'];
//Upload a photo to album of ID...
$photo_details = array(
'message'=> 'SEGUICI SU CASE DA SOGNO https://www.facebook.com/pages/Case-da-sogno/575064225848397?ref=hl',
'access_token' => $page_info['access_token']
);
//TROVO L'IMMAGINE DA CARICARE
//Imposto la directory da leggere
$directory = "prova/";
$results = array();
// Apriamo una directory e leggiamone il contenuto.
if (is_dir($directory))
{
//Apro l'oggetto directory
if ($directory_handle = opendir($directory))
{
//Scorro l'oggetto fino a quando non è termnato cioè false
while (($file = readdir($directory_handle)) !== false)
{
//Se l'elemento trovato è diverso da una directory
//o dagli elementi . e .. lo visualizzo a schermo
if((!is_dir($file))&($file!=".")&($file!=".."))
{
//echo $file . "<br/>";
array_push($results, $file);
}
}
//Chiudo la lettura della directory.
closedir($directory_handle);
}
}
$cont= 0;
date_default_timezone_set('Europe/Rome');
while($cont<count($results))
{
$ora = ($cont+1)*12;
$file = $directory.$results[$cont];
$photo_details['image'] = '#' . realpath($file);
$tempo_pubblicazione = date("Y-m-d H:i:s", strtotime ("+$ora minutes"));
$pubblica_ora_data = strtotime($tempo_pubblicazione);
echo "<br>ORA=".$pubblica_ora_data;
$photo_details['scheduled_publish_time'] = "$pubblica_ora_data";
$photo_details['published'] = "0";
$upload_photo = $facebook->api('/'.$album_uid.'/photos', 'post', $photo_details);
$file = $directory.$results[0];
unlink($file);
echo "<br>".$results[$cont];
$cont++;
}