Menu
  • HOME
  • TAGS

Is it possible to change ONE line in a txt file WITHOUT reading and writing the whole file (Java)?

java,file,text,replace,line

Short answer: no. Long answer: Not really. If you know that the text you're inserting directly replaces the text you're removing you could perform a substitution by seeking to the portion of the file, reading a small block, substituting the new text and replacing that block. This would work for...

Regex capture and replace %20 after last forward slash

regex,bash,perl,replace,command-line

replace %20 after last forward slash of href attributes of non .jpg links You can use the following to match: %20(?=(?:(?!\.jpg">)[^>\/])*>) And replace with - See DEMO...

Find and replace in an AS3 String

string,actionscript-3,replace,find

You need to mask "(" and "*" in your pattern: var pattern:RegExp = /\(\*/gi; ...

jquery losing value of $(this) on ajax request [duplicate]

javascript,jquery,ajax,replace

You need to preserve $(this) in a variable for the callback like var $link = $(this); $.ajax({ type : "POST", cache : false, url : $(this).attr('href'), data : $(this).serialize(), success : function(data) { $('.loading-icon').hide(); $link.attr('href').replace(/delete/, 'add'); $link.removeClass('remove-favourite').addClass('add-favourite'); } }) this itself will have changed because the execution context of the...

String Replace Java Function

java,string,class,replace,bukkit

Your problem is, most likely, because you expect that your function mutates the original String you passed to the method. Strings are immutable in java, and besides, you cannot modify the original reference you pass to method from that method. To get the result you most likely expect, store returned...

Replace All Words In Document Body Doesn't Work

javascript,replace

no need to iterate body element try this: want to change to with that js? i have used to make it function addTitleToSurveyUrls() { var elements = document.getElementsByTagName('a'); for(var el in elements) { var element = elements[el]; var href = element.getAttribute("href"); if(href.indexOf('survey_')>-1) { element.setAttribute('title', 'Some TITLE HERE'); } } }...

Find and replace entire value in R

regex,r,replace

You can use gsub as follows: gsub(".*experiences.*", "exp", string, perl=TRUE) # As @rawr notes, set perl=TRUE for improved efficiency This regex matches strings that have any characters 0 or more times (i.e. .*) followed by "experiences", followed by any characters 0 or more times. In this case, you are still...

Fastest way to remove 'extra' spaces (more than 1) from a large range of cells using VBA for excel

excel-vba,replace,trim,spaces

The loop is killing you. This will remove spaces in an entire column in one shot: Sub SpaceKiller() Worksheets("Sheet1").Columns("A").Replace _ What:=" ", _ Replacement:="", _ SearchOrder:=xlByColumns, _ MatchCase:=True End Sub Adjust the range to suit. If you want to remove double spaces, then: Sub SpaceKiller() Worksheets("Sheet1").Columns("A").Replace _ What:=" ", _...

Looping Over a String Gives Segmentation Fault

c++,string,replace,lowercase

Turning on the warnings, you may spot the error yourself: g++ -o main main.cpp -Wall Errors: main.cpp: In function ‘std::string lowercase(std::string)’: main.cpp:9:21: warning: comparison between signed and unsigned integer expressions [-Wsign-compare] for (int i=0; i < ans.size(); i++) ^ main.cpp:14:1: warning: no return statement in function returning non-void [-Wreturn-type] }...

Replace values in column of a dataframe based on overlap with a vector

r,for-loop,replace

#addones lstcol <- list('cola', 'colb') lstvec <- list(veca, vecb) myfunc <- function(COL, VEC) { dataframe[[COL]][dataframe$ID %in% VEC] <<- 1 } for(i in 1:length(lstcol)) { myfunc(lstcol[[i]], lstvec[[i]]) } dataframe # ID cola colb colc cold cole colf #1 XXXYYY 1 0 0 0 0 0 #2 XXYYXX 1 0 0 0...

MySQL wildcard replace

mysql,replace,wildcard,placeholder

Using SUBSTRING_INDEX: UPDATE table1 SET column1 = REPLACE( column1, SUBSTRING_INDEX(column1, '/', 2), 'newsite.com' ) WHERE column1 LIKE 'example.com/%/' This should honour your subfolder structure....

Microsoft Word 2010 VBA: Using regex to find and replace

regex,replace,ms-word,word-vba,pci

Since it seems like you are using the Word wildcard syntax, you probably can use <, which asserts beginning of word, and >, which asserts end of word to prevent the pattern from matching when the text is preceded or succeeded by letters or numbers (which is how it seems...

Replace the contents of a vector with the values of a matrix

r,matrix,vector,replace

Try match where 'm1' is the matrix match(vector1, m1[,1]) #[1] 2 1 2 3 Or unname(setNames(as.numeric(m1[,2]), m1[,1])[vector1]) #[1] 2 1 2 3 ...

Powershell For Loop, Replace, Split, Regex Matches

regex,powershell,replace,split

Leveraging the power in PowerShell we can turn the output of pnputil into an object array that will make it much easier to parse the data you are looking for (since it appears you are looking for something specific). Each entry is a group of variables with a blank line...

Extract Cells content in the first Excel File based on Worksheet in another File

excel,function,excel-vba,replace

This is the literal translation of what you shown : Sub MacroClear() Dim wbD As Workbook, _ wbC As Workbook, _ wsD As Worksheet, _ wsC As Worksheet, _ Dic() As String 'Replace the names in here with yours Set wbD = Workbooks("Dictionnary") Set wbC = Workbooks("FileToClean") Set wsD =...

Replace special qoutes with normal

vb.net,replace,utf-8

Unfortunately VB.NET doesn't support escape sequences but you can use ChrW() to specify code point: s = s.Replace(ChrW(&H201C), """") That's for “, code for ” is &H201D. Note that using code points you're free to search & replace any Unicode character (not just what VB.NET has an escape for -...

Batch-Script: Replace every “@” in file name with “_” in network drive including subfolders

batch-file,replace,folder,filenames

setsyntax for replacing a string: set "var1=my old hat" set "var2=%var1:old=new%" echo %var1% was better than %var2% To get all txt-files: for %%i in (*.txt) do ( echo %%i rem substitution does not work with special %%i variable type set "oldname=%%i" set "newname=!oldname:@=_!" echo rename "!oldname!" "!newname!" ) Why !...

How to replace newlines/linebreaks with a single space, but only if they are inside of start/end regexes?

regex,linux,shell,unix,replace

You can do it using awk as: awk '/\[x/{f=1} {if(f)printf "%s",$0; else print $0;} /y\]/{print ""; f=0}' Output: [x data1 data2 data3 data4 y] [a data5 data 6 data7 data 8 b> [x data y] You can also simplify to: awk '/\[x/,/y\]/{ORS=""; if(/y\]/) ORS="\n";}{print}' Output: [x data1 data2 data3 data4...

Replacing alternate spaces with newline?

unix,replace

awk might help in this case: echo "0 1 2 3 4 5" | awk ' { for (i=1; i<=NF; i++) { if ((i-1)%2 == 0) { printf "%d ",$i; } else { print $i } } } ' We split by space and have 6 items. We, then, are...

javascript replace dot (not period) character

javascript,regex,replace

Try using the unicode character code, \u2022, instead: message.replace(/\u2022/, "<br />\u2022"); ...

Return what was replaced in SQL

sql,sql-server,regex,tsql,replace

You could try the output keyword, that won't tell you exactly what was taken out but it will tell you the state of the record before you changed it. And yes, it would work better for you if the information was properly normalized. UPDATE table SET a = replace..... OUTPUT...

Replace the characters in every line of a file, if it match a condition - Unix

unix,replace,sed,match,condition

There is no need to loop through the file with a bash loop. sed alone can handle it: $ sed -r '/^.{14}R.{12}D/s/(.{52}).{4}/\10000/' file 05196220141228R201412241308D201412200055SA1155WE130800001300SL07Y051 05196220141228R201412241308A201412220350SA0731SU1950LAX C00020202020 05196220141228R201412241308D201412200055SA1155WE130800005300SL07Y051 05196220141228N201412241308A201412240007TU0548WE1107MEL C00000000015 07054820141228N201412220850D201412180300TH1400MO085000040300UL180001 This uses the expression sed '/pattern/s/X/Y/' file:...

How to replace href inside of
  • using jQuery
  • jquery,replace,html-lists,href

    $("li #ctl01_Auxiliary_Auxiliary_rptWrapper_Auxiliary_rptWrapper_rpt_ctl01_Navigat‌​ion‌​Link").attr("href", "/Public/Cart") ...

    How to alter dynamic/live element attributes - (replaceWith()) used

    jquery,dynamic,replace,live

    I think the only thing you're maybe not wrapping your head around is the idea of callbacks and asynchronous methods. You're currently running your console.log statements before the replaceWith occurs. The function() { } block (your "callback") passed as the second parameter to $.get doesn't execute until the AJAX call...

    Replace list of emojies in JavaScript

    javascript,jquery,regex,replace

    join your array and create a single regex, then you can use replace with a callback function (or use the single line replace like in sln's answer) to create the spans Note this assumes all emoji names are between : var emojies = ["smile", "smiley", "grin", "joy"]; //Create a single...

    Replace numbers with Boolean in r

    r,csv,replace,weka

    The function as.logical will coerce any non-zero number to TRUE and zero to FALSE. Assuming your CSV has been loaded into a data frame called boxdata with the same column names as in the CSV: ifelse(as.logical(boxdata$Receiver_TotalVideoDecoderErrors), 'Error', 'No error') Or you can use broadcasting to do the work for you....

    Python - Opening and changing large text files

    python,replace,out-of-memory,large-files

    You need to read one bite per iteration, analyze it and then write to another file or to sys.stdout. Try this code: mesh = open("file.mesh", "r") mesh_out = open("file-1.mesh", "w") c = mesh.read(1) if c: mesh_out.write("{") else: exit(0) while True: c = mesh.read(1) if c == "": break if c...

    Replace forward slash with jQuery

    javascript,regex,string,replace

    This will do it (without jQuery): var str = 'hello/page/2/bye'; str = str.replace(/page\/\d+\//,''); The slashes need to be escaped (so they become \/), \d+ is any number, one or more times (so it also matches e.g. page/12/ Demo: http://jsfiddle.net/dd5aohbc/...

    Replace string to the target format

    .net,regex,vb.net,string,replace

    It is impossible to achieve in a single pass. I suggest: Adding parentheses: (\p{Lu}+)\s*(\p{Lu}+)(.*) (replace with $1($2$3)) See demo Then, you can use a regex to find all spaces between numbers and replace them with a comma: (?<=\d+)\s+(?=\d+). See demo (see Context tab). Here is a working VB.NET code: Dim...

    Select Concat Substring and Replace in MySQL

    mysql,string,replace,concat

    How about substring_index()? UPDATE `questions` SET answer = substring_index(substring_index(answer, '"', 2), '"', -1) ...

    Delete word from a line in a text file

    java,string,file,replace

    The replace(...) method doesn't modify the original String, it returns a new modified String. You need to do something like this: line = line.replace(" alle ", " "); And here is a complete solution: Scanner scannerLines = new Scanner(file); boolean alleFound = false; boolean nrFound = false; boolean minFound =...

    Java replace every Nth specific character (e.g. space) in String

    java,regex,string,replace

    You can use the "last match or beginning of line" trick in a positive look-behind: String s = "I have been stuck on this problem forever quick brown fox jumps over"; String r = s.replaceAll("(?<=(^|\\G)\\S{0,100}\\s\\S{0,100}\\s\\S{0,100})\\s", "_"); System.out.println(r); The unfortunate consequence of using a look-behind is that you need to provide...

    Strategy for Processing a Text File with a Header using Reg Exp in Java

    java,regex,replace

    Assuming you can use java.nio.file.Files (since Java 1.7) and your text file isn't too big, I'd read all lines at once and go for the Matcher: Charset charset = Charset.forName("UTF-8"); List<String> lines = Files.readAllLines(file.toPath(), charset); for (String line : lines) { Matcher matcher = regexpPattern.matcher(line); if (matcher.matches()) { // do...

    converting [b] to

    php,replace

    This might be done more simply using str_replace() $search = array('[b]', '[/b]', '[i]', '[/i]'); $replace = array('<b>', '</b>', '<i>', '</i>'); str_replace($search, $replace, $string ); ...

    How to remove all characters before a specific character in Python?

    python,string,replace

    Use re.sub. Just match all the chars upto I then replace the matched chars with I. re.sub(r'.*I', 'I', stri) ...

    How to Avoid the string from number(for rupees) in c#?

    c#,wpf,c#-4.0,replace,decimal

    Here you go: string OnlyNumbered = Regex.Match(label1.Content.ToString(), @"\d+").Value; ...

    JS RegEx challenge: replacing recurring patterns of commas and numbers

    javascript,regex,replace

    The easiest way is to isolate sequences like 15、18 and replace all commas in them. text = "3条4~12丁目、15~18条12丁目、2、3条5丁目"; text. replace(/(?:\d+、)+\d+/g, function(match) { return match.replace(/、/g, "&"); }). replace(/条/g, '-jō '). replace(/丁目/g, '-chōme'). replace(/~/g, '-'). replace(/、/g, ', ') // => "3-jō 4-12-chōme, 15-18-jō 12-chōme, 2&3-jō 5-chōme" (Also... Where the heck do you...

    Regex Lookahead/behind to find character unless followed by the same

    regex,vb.net,replace,replaceall

    Let me explain why your regex does not work. \\ - Matches \ (?=[0]) - Checks (not matches) if the next character is 0 (?<![\\]) - Checks (but not matches) if the preceding character (that is \) is not \. The last condition will always fail the match, as \...

    How to extract single-/multiline regex-matching items from an unpredictably formatted file and put each one in a single line into output file?

    linux,shell,unix,replace,grep

    Assuming that your document is well-formed, i.e. <b> opening tags always match with a </b> closing tag, then this may be what you need: sed '[email protected]<[/]\?b>@\n&\[email protected]' path/to/input.txt | awk 'BEGIN {buf=""} /<b>/ {Y=1; buf=""} /<\/b>/ {Y=0; print buf"</b>"} Y {buf = buf$0} ' | tr -s ' ' Output: <b>data1</b>...

    Javascript Replace function not working on first instance

    javascript,jquery,string,if-statement,replace

    The problem is with the check of tagcounter <= 0. When you are checking that for the first time, tagcounter is still 1. You decrement it later. Hence the "+" never gets appended. Hence when you are trying to remove "+Light" it doesn't work because the "+" is not there...

    Xpath for Find & Replace?

    xml,xpath,replace

    XPath cannot modify an XML file. For that you need XSLT or XQuery. If this really is a global change (that is, if you want to change this text regardless of the context where it appears) then I would be very inclined myself to do it using a text editor:...

    Python: Replace “wrong” floats by integers inside string

    python,string,replace,floating-point,integer

    (?<=\d)\.0+\b You can simple use this and replace by empty string via re.sub. See demo. https://regex101.com/r/hI0qP0/22 import re p = re.compile(r'(?<=\d)\.0+\b') test_str = "15.0+abc-3" subst = "" result = re.sub(p, subst, test_str) ...

    stringByReplacingCharactersInRange does not work?

    ios,string,swift,replace

    You don't need to cast it to NSString to use stringByReplacingCharactersInRange you just need to change the way you create your string range as follow: let binaryColor = "000" let resultString = binaryColor.stringByReplacingCharactersInRange( Range(start: binaryColor.startIndex, end: advance(binaryColor.startIndex, 1)) , withString: "1") println("This is binaryColor: \(resultString)") ...

    Search for string in file while ignoring id and replacing only a substring

    python,regex,string,replace

    One way to do this is to have a function for replacing text. The function would get the match object from re.sub and insert id captured from the string being replaced. import re s = 'ref_layerid_mapping="x4049" lyvis="off" toc_visible="off"' pat = re.compile(r'ref_layerid_mapping=(.+) lyvis="off" toc_visible="off"') def replacer(m): return "ref_layerid_mapping=" + m.group(1) +...

    JS: Adding a space between Japanese character phrase and number using regex

    javascript,regex,replace

    s.replace(/(丁目)(?=\d)/g, "$1 ") This should do it for you.Your earlier regex was not working cos if ?: which makes it non capturing and $1 had nothing in it.See demo. https://regex101.com/r/nS2lT4/10 var re = /(丁目)(?=\d)/g; var str = '北23条東12丁目5-30-405'; var subst = '$1 '; var result = str.replace(re, subst); ...

    Swift - how to convert hyphen/minus sign into + sign

    string,swift,replace,converter

    tmpAddress = tmpAddress.stringByReplacingOccurrencesOfString("-", withString: "+") This replaces '-' with '+' The first parameter is the search string, and the second is the replacement string....

    Replacing values in a matrix by specified values

    matlab,for-loop,replace

    Try it like this: for i=1:nIndices slice = simulatedReturnsEVT1(:,i,:); slice(slice < MinAcceptableVal(i))=MinAcceptableVal(:,i); slice(slice > MaxAcceptableVal(i))=MaxAcceptableVal(:,i); simulatedReturnsEVT1(:,i,:) = slice; end ...

    How do I replace certain PHP values with my own text?

    php,arrays,string,wordpress,replace

    The Verbose Way: You're close...But I'd simplify a bit and forego the str_replace(). I'd do something like the following: $shipping_method = $order->get_shipping_method(); if ( $shipping_method === 'Free Shipping' ) { $shipping_method = 'Free'; } elseif ( $shipping_method === 'FedEx_GROUND' ) { $shipping_method = 'FedEx'; } elseif ( $shipping_method === 'UPS...

    String.replace() isn't working like I expect

    java,string,replace

    The replace method isn't changing the contents of your string; Strings are immutable. It's returning a new string that contains the changed contents, but you've ignored the returned value. Change example.replace(oldNumber, newNumber); with example = example.replace(oldNumber, newNumber); ...

    Change/replace part of an URL contained WITHIN a function

    javascript,replace,google-spreadsheet

    Instead of including DATA1 in the URL, append it with data coming from f.ex a textbox: function loadChart() { var txtbox = document.getElementById('textbox').value; var url = 'https://docs.google.com/spreadsheet/ccc?key=...&sheet=' + txtbox; var query = new google.visualization.Query(url); query.send(handleQueryResponse); } ...

    Regular expression to remove everything but words. java

    java,regex,string,replace

    public static String filter(String input) { return input.replaceAll("[^A-Za-z0-9' ]", "").replaceAll(" +", " "); } The first replace replaces all characters except alphabetic characters, the single-quote, and spaces. The second replace replaces all instances of one or more spaces, with a single space....

    Replacing elements in an HTML file with JSON objects

    javascript,json,replace

    obj.roles[0] is a object {"name":"with whom"}. you cant replace string with object. you need to refer to property "name" in the object obj.roles[0].name Another problem is that var finalXML get a new value every line. you need to add a new value to the variable, not replcae it. var finalXML...

    String replace with integer not working [closed]

    java,string,replace,integer,replaceall

    The replace only works on the first execution. After that, value no longer contains -time-. As a solution, you can use a temporary variable to do your replacement: String displayValue = value.replace("-time-", time + ""); ...

    how to replace NumberInt(1) to 1 with vim?

    regex,vim,replace

    You can try: :%s/\vNumberInt\((\d+)\)/\1/ Using very magic mode (\v), do grouping in the number between parentheses and use it in the replacement part as backreference (\1): It yields: "bz":1, "something": "something else NumberInt(1)" "bz":1, "something": "something else NumberInt(2)" "bz":1, "something": "something else NumberInt(3)" "bz":1, "something": "something else NumberInt(4)" "bz":1, "something":...

    Jquery allow only float 2 digit before and after dot

    jquery,regex,replace

    Try setting input maxlength to 5 ; utilizing .val(function(index, val)) ; RegExp /\d{3}|[^\d{2}\.]|^\./ $("#valueSconto").on("input", function() { $(this).val(function(i, val) { return val.replace(/\d{3}|[^\d{2}\.]|^\./g, ""); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <input type="text" id="valueSconto" maxlength="5" /> ...

    Regex to remove `.` from a sub-string enclosed in square brackets

    c#,.net,regex,string,replace

    To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

    how to replace strings in a file by other strings in java

    java,string,file,replace

    First of all, the code you wrote here is not working, because when you open an outputStream to the exact file you try read from, it will empty the source file and the statement in.readLine() always returns null. So if this is your real code maybe this is the problem....

    Replace text between two special characters

    regex,r,text,replace

    Try sub('(?<=").*(?=")', y, x, perl=TRUE) #[1] "\t\t<taxon id=\"TOT_A01\"/>" ...

    How can I fix the following sed command?

    regex,linux,unix,replace,sed

    In order to only match your lm words and not affect the following ones, you need to restrict the pattern. I suggest turning .* to [^[:blank:]]* to match 0 or more characters other than spaces or tabs: sed 's/\([^_]lm[01?]_[^[:blank:]]*\)\([ (]\)/\1_out\2/g' text_to_edit (EDIT) Or, if the only characters there are between...

    Notepad++ - Find and replace both opening and closing tags while keeping the content intact?

    regex,replace,notepad++

    Find what: \\section\{(.+)\} Replace with: <h1>\1</h1> Here, the parentheses (.+) define a group that consists of one or more character, and \1 references the contents of the group....

    find common string in two text files using batch script

    string,parsing,batch-file,search,replace

    Not sure about the requirements, but, maybe awk "{print $1}" 2.txt | findstr /g:/ /l /b 1.txt Without awk cmd /q /c"(for /f "usebackq" %%a in ("2.txt") do echo(%%a)" | findstr /g:/ /l /b 1.txt Only awk awk "{a[$1]=!a[$1]} !a[$1]" 2.txt 1.txt ...

    Replace method that adds an incrementing number to a repeated string

    javascript,node.js,methods,replace

    I don't think you want to loop. Try doing a global regex with the incrementing number in the replace pattern: function(doc) { var number = 1; return doc.replace(/(<a\s+[^>]*id="r)("[^>]*>[^<]*<\/a>)/gi, function(m, a, b) { return a + (number++) + b; }); }; This looks for any <A> tags with id="r", keeps their...

    Replace a random block of characters in a string in R

    regex,r,replace

    > library(stringr) > mystring <- "\t\t\tFGHGFJKJKJKGDSJS" > x <- "ABCCCBBHHJJJH" > str_replace(mystring,"\\w+",x) [1] "\t\t\tABCCCBBHHJJJH" \w+mean match any character or number or underscore at least once and as many as possible. So each part not a normal char will be replace by your x variable....

    Replace string :"{ using regex

    .net,regex,replace

    I'm pretty sure that you don't need a regular expression for this. Just use var str2 = str.Replace(":\"{", ":{").Replace("}\"", "}"); ...

    Replace string if the string is not part of a larger string using regex in javascript

    javascript,php,regex,string,replace

    Something like this? ( °_• ) var txt="or some text or before (.)or(.) anywhere Or"; console.log(txt.replace(/\bor\b/gi,"OR")); // "OR some text OR before (.)OR(.) anywhere OR" ...

    Text replacement from a string in php

    php,arrays,regex,string,replace

    That's a simple search and replace for your defined markers. $text = 'Hello World [this-echo] Hello Everybody [nobody]'; $markers=array('[this-echo]','[nobody]'); $replacements=array('Today','Anybody'); $text= str_replace($markers,$replacements,$text); Output Hello World Today Hello Everybody Anybody Fiddle...

    Sphinxql Replace() function like mysql

    replace,sphinx,sphinxql

    ignore_chars seems to be a perfect fit for this... http://sphinxsearch.com/docs/current.html#conf-ignore-chars...

    Replace every occurence of [b: “text”] to text where text can be anything

    javascript,regex,replace

    You need to use a capturing group ((.*)) to match the text between the quotes and use that in your replacement. Note that if you have to handle escaped quotes inside the string or anything complex, you'll want to use a real parser rather than complicating the regex more (I'd...

    SQL bypass REPLACE by CASE statement

    sql-server,tsql,replace,case,sql-server-2014

    It is obvious that '' means blank (Not null) and it exists between two consecutive letters also. (As it is blank) So Sql can not go on replacing that blank in between every letter with the string you want. That's why you can not replace '' Check this query SELECT...

    Replace integers in a string using Visual Basic

    vb.net,string,replace,integer

    You have to use a regex object like this: C# string input = "This is t3xt with n4mb3rs."; Regex rgx = new Regex("[0-9]"); string result = rgx.Replace(input, "Z"); VB Dim input As String = "This is t3xt with n4mb3rs." Dim rgx As New Regex("[0-9]") Dim result As String = rgx.Replace(input,...

    how to convert (replace) a symbol to a html tag [closed]

    javascript,php,jquery,regex,replace

    You can use the following to match: \*\*([^*]*)\*\* And replace with: <strong>$1</strong> $1 - It is the back reference to the first capture group ([^*]*).. basically telling the regex to replace with whatever was captured between first set of parentheses ( ) See DEMO JScode: var str='test1 **test2** test3'; str...

    Using ant.replace in gradle

    replace,ant,gradle

    It should be: task writeVersion << { ant.replace( file: 'version.txt', token: 'versionNumber', value: '1.0.0' ) } and: version.number=versionNumber ...

    Search and replace all php_short_tag that is

    php,regex,replace,php-shorttags,shorttags

    Just make the = symbol as optional one. preg_replace('~<\?=?(?!php\b)~', '<?php ', $str); OR preg_replace('~<\?=?(?!php\b)(\w)~', '<?php \1', $str); DEMO...

    Powershell variable in replacement string with named groups

    regex,powershell,replace

    @PetSerAl comment is correct, here is code to test it: $sep = "," "AAA BBB" -Replace '(?<A>\w+)\s+(?<B>\w+)',"`${A}$sep`${B}" Output: AAA,BBB Explanation: Powershell will evaluate the double quoted string, escaping the $ sign with a back tick will ensure these are not evaluated and a valid string is provided for the -Replace...

    Substitute string in BASH with Sed (when it has special characters)

    bash,replace,sed

    It is generally not a good idea to iterate over the output of find since file names can contain the $IFS which would break the loop. Use the -exec option of find instead: find -iname 'PATCH*' -exec sed -i 's#`which cat`#/bin/cat#g' {} \; ...

    PHP Replace binary file at hex address [closed]

    php,replace,binary,hex,preg-replace

    If the string is at fixed position, you can write data directly: $position=hexdec("00010edb"); // You have to pre-calculate it once $data="some data"; // Replacement if ($f=fopen("your_file", "r+")) { fseek($f, $position); fwrite($f, $data); fclose($f); } else { echo "Can't open file"; } ...

    Return value based on duplicate columns

    mysql,sql,replace,duplicates

    You can try with group by: select Firstname , Lastname , case when count(*) > 1 then '**ERROR**' else age end from Table group by Firstname , Lastname , age; Or in case you want to return all rows with duplicates: select t.Firstname , t.Lastname , case when (select count(*)...

    conditional replace based off prior value in same column of pandas dataframe python

    python,pandas,replace,fill,calculated-columns

    Here's a kind of brute-force method. There is probably something more elegant, but you could explicitly loop over the rows like this: df = pd.DataFrame([0, -1, -1, -1, 0 , 0, 0, 1, 0]) df.columns = ['A'] df['B'] = df['A'] # loop here for i in range(1,len(df)): if df.A[i] ==...

    Calling bash function in perl find replace

    bash,perl,replace

    You don't need bash and unnecessary piping through multiple system utilities, perl -i -pe' BEGIN { @chars = ("a" .. "z", "A" .. "Z", 0 .. 9); push @chars, split //, "[email protected]#$%^&*()-_ []{}<>~\`+=,.;:/?|"; sub salt { join "", map $chars[ rand @chars ], 1 .. 64 } } s/put your...

    What is a regular expression for inserting a string into a Find and Replace match?

    c#,regex,replace

    You will need to put the value that is between the square brackets into a capture group, and substitute that in your replacement. In short, this will do it: Regex.Replace(input, @"Session\[(""\w+"")]\s==", @"Session[$1].ToString() =="); where $1 will insert the contents of your first capture group (determined by parenthesis in the pattern...

    Using R to repeatedly replace words

    r,loops,replace

    You could construct a simple loop and print using cat. for (i in 1:length(day)) { cat("Today is", day[i], "and it is a", weather[i], "day.\n") cat(day[i], "is a", weather[i], "day\n") } # Today is Monday and it is a sunny day. # Monday is a sunny day # Today is Tuesday...

    Replace characters in java string [duplicate]

    java,replace

    replace doesnt use a regular expression. Just use myString = myString.replace("[merchant]", "newText"); ...

    shell script for counting replacements

    bash,replace,count

    Assuming you want to replace the word 'apple' with 'banana' (exact match) in the contents of the files and not on the names of the files (see my comment above) and that you are using the bash shell: #!/bin/bash COUNTER=0 for file in *.txt ; do COUNTER=$(grep -o "\<apple\>" $file...

    Efficient means of mass converting >600,000 different find and replaces within one file

    replace

    Python code, assuming your substitutions are stored in subs.csv: import csv subs = dict(csv.reader(open('subs.csv'), delimiter='\t')) source = csv.reader(open('all_snp.map'), delimiter='\t') dest = csv.writer(open('all_snp_out.map', 'wb'), delimiter='\t') for row in source: row[1] = subs.get(row[1], row[1]) dest.writerow(row) The line row[1] = subs.get(row[1], row[1]): row[1] is the Affx column, and it replaces it with a...

    Regex replace linebreak and comma

    javascript,regex,replace

    There have been a lot of responses to this question and for a newbie to regex it is probably a bit overwelming, Overall the best response has been: var str2 = str.replace(/^,/gm, ''); This works by using ^, to check if the first character is a comma and if it...

    replace() function recodes entire column

    r,replace

    replace operates on vectors, not data.frames. Try this: > replace(df$Group.1,df$Group.1 == 1, "male") [1] "male" "2" And to change the data, you can do: > df$Group.1 <- replace(df$Group.1,df$Group.1 == 1, "male") > df Group.1 x 1 male 4000 2 2 3890 What you are trying to do looks like a...

    RegEx replace returns unexpected result without .*

    javascript,regex,replace,capture-group

    I would do like, > "Apple Orange".replace(/(?:^|\s)([A-Z])|./g, "$1") 'AO' Don't complex the things. Just capture all the uppercase chars which exists just after to a space or at the start. And then match all the remaining characters. Now replace all the matched chars by $1. Note that all the matched...

    Splitting string before name of month with regex

    python,regex,python-2.7,replace,data-cleaning

    You should be able to do this with a one RegeEx for all months: import re lines = [ "Yes, I'd say so. Nov 08, 2014 UTC", "Hell yes! Oct 01, 2014 UTC" ] for ln in lines: print re.sub(r'(\w+\s\d{2}, \d{4} UTC)$', r'\t\1', ln) Which will return: Yes, I'd say...

    How do i remove the large leading space in the output of this code for variable a

    java,string,replace

    The leading spaces are for multiple reasons: When you remove expletives, they are surrounded by spaces, that are not removed. You could capture your expletives using the following regex instead: \baaaa[^a-zA-Z]? This regex will capture a word boundary, followed by the expletive (replaced with aaaa here), and then an optional...

    How to do replace multiple times ? php

    php,string,replace,str-replace,php-5.3

    You can't achieve this by str_replace. Use string translation (strtr) which was designed to do so instead: $words = 'word1 word2'; $wordsReplaced = strtr($words, [ 'word1' => 'word2', 'word2' => 'word1' ]); ...

    Replace backslash in string

    java,regex,string,exception,replace

    Use four backslashes to match a single backslash character. String texter = texthb.replaceAll("\\\\.+?\\\\", "\\\\"+String.valueOf(pertotal + initper)+"\\\\"); ...

    Regular expression, match error

    regex,replace,match

    You can dispense with most of your pattern - much of it is unnecessary. Try this: <img.*?> With the unnecessary brackets removed, the important change is adding ? to make it a reluctant quantifier - one that matches as little as possible....

    Using regex to extract multiple strings

    regex,xml,string,replace

    Just use parentheses instead of braces. Regex.Replace(str, @"<(jv:(?:FirstName|MiddleInitial|LastName)>).*?</\1, "<$1</$1"); Braces signify matching any character within them one time. Parentheses match the full string....

    LabVIEW variables Find and Replace

    variables,replace,labview

    You can rebind local variables from one control or indicator to another using VI Scripting. Place this code in a new VI: This opens a reference to the VI whose locals you want to rebind, gets a reference to the VI's front panel, gets a reference to the control on...