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

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

Related

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

VBA Code is picking up a column not called out

Sub UpdateDMDCLCSIM()
Dim SIM_DM_DCLC As Worksheet
Dim TextFileUpdated As Date
Set SIM_DM_DCLC = ThisWorkbook.Sheets(Sheet52.Name)
TextFileUpdated = DateValue(FileDateTime("\\networkshare\dept\DCGSI\Extracts\SIM_DM_DCLC.csv"))
Application.DisplayAlerts = False
Application.StatusBar = "Importing latest DM DCLC SIM Data..."
With SIM_DM_DCLC.QueryTables.Add(Connection:= _
"TEXT;\\networkshare\dept\DCGSI\Extracts\SIM_DM_DCLC.csv" _
, Destination:=SIM_DM_DCLC.Range("$A$1"))
.Name = "SIM_DM_DCLC"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 936
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
'Change to MySQL date format.
SIM_DM_DCLC.Range("I:K", "P:T").Replace Chr(84), " "
SIM_DM_DCLC.Range("I:K", "P:T").Replace Chr(90), ""
SIM_DM_DCLC.Range("I:K", "P:T").NumberFormat = "yyyy-mm-dd hh:mm:ss"
Okay so this opens a csv that is downloaded to a network share and fixes some dates. The dates in the original file are formatted YYYY-MM-DDTHH:MM:SSZ and this is supposed to strip the T and Z from those dates in the appropriate columns. The issue I am having is that for some strange reason it is processing column L in the file and I can't figure out why.
So I looked up some code for regex replace in VBA and tried to refactor the code to use the following code to try and fix the issue:
Sub UpdateDMDCLCSIM()
On Error GoTo ErrorHandler
Dim SIM_DM_DCLC As Worksheet
Dim TextFileUpdated As Date
Set SIM_DM_DCLC = ThisWorkbook.Sheets(Sheet52.Name)
TextFileUpdated = DateValue(FileDateTime("\\networksharem\dept\DCGSI\Extracts\SIM_DM_DCLC.csv"))
Application.DisplayAlerts = False
Application.StatusBar = "Importing latest DM DCLC SIM Data..."
With SIM_DM_DCLC.QueryTables.Add(Connection:= _
"TEXT;\\networkshare\dept\DCGSI\Extracts\SIM_DM_DCLC.csv" _
, Destination:=SIM_DM_DCLC.Range("$A$1"))
.Name = "SIM_DM_DCLC"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 936
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
'Change to MySQL date format.
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z)$/"
For Each cell In SIM_DM_DCLC.UsedRange
If cell.Value <> "" Then cell.Value = regex.Replace(cell.Value, "/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/")
Next cell
Pretty sure that the 5017 - Application-defined or object-defined error I am getting on the regex.Replace means I have something wrong with the regex piece. Just not sure what it is.
Well you have to check to an actual match and not just a blank; here is the updated and appropriate section of code.
'Change to MySQL date format.
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z)$"
For Each cell In SIM_DM_DCLC.UsedRange
If cell.Value = regex.Pattern Then cell.Value = regex.Replace(cell.Value, "^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$")
Next cell

VBA Using regex for replacing stuff

I never did VBA before, and I am not skilled in programming in any way xD
I am trying do remove some things from a list that contains html descriptions, but it is not working.
Any advice what horrible things I did wrong here?
Function entferne_sonstige_zeichen(description)
entferne_sonstige_zeichen = description
Dim oRegExp As RegExp
Set oRegExp = New RegExp
With oRegExp
.IgnoreCase = False
.Global = True
.MultiLine = True
.Pattern = "[^A-Za-z\d,/-]"
End With
Dim ReplacePattern As String
ReplacePattern = ""
description = oRegExp.Replace(ReplacePattern)
End Function
Maybe...
Function entferne_sonstige_zeichen(str As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
.IgnoreCase = False
.Global = True
.MultiLine = True
.Pattern = "[^A-Za-z\d,/-]"
.ignorecase = True
entferne_sonstige_zeichen = .Replace(str, vbNullString)
End With
End Function

VBScript Regexp Does Not Give Result As Expected

Dim regEx
Set regEx = New RegExp
With regEx
.Pattern = "\[QUOTE=(.*?)\](.*?)\[\/QUOTE\]"
.IgnoreCase = True
.Global = True
.MultiLine = True
End With
string1="[QUOTE=P2]A[/QUOTE]B[QUOTE=P3][QUOTE=P1]C[/QUOTE]D[/QUOTE]E"
response.write regEx.Replace(string1, "")
I want BE as a result but I get BD[/QUOTE]E
Where is the problem?
Just do some conversions step by step to get the necessary structure, then retrieve result:
string1 = "[QUOTE=P2]A[/QUOTE]B[QUOTE=P3][QUOTE=P1]C[/QUOTE]D[/QUOTE]E"
With New RegExp
.IgnoreCase = True
.Global = True
.MultiLine = True
.Pattern = "\[QUOTE=(.*?)\]"
string1 = .Replace(string1, "[")
.Pattern = "\[\/QUOTE\]"
string1 = .Replace(string1, "]")
.Pattern = "\[[^[]]*?\]"
Do While .Test(string1)
string1 = .Replace(string1, "")
Loop
End With
response.write string1

Removing tabs and newlines with regular expressions issue

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') + "'")