Find a text between double quotation in ruby by gsub - regex

I wanna find a text in the text file by gsub in ruby and change it like this:
My text in main file:
set description "alas-cd002-ak"
And I wanna change it to below:
<desc>alas-cd002-ak</desc>
So I used below command but it didn't work:
text.gsub!(/\sset\sdescription\s"(?<name>^[a-zA-Z0-9_.-]*$)"/,'<desc>\k<name></desc>')
Please help me fix my gsub code. also I'm new in Ruby.

The best approach is to use a regular expression, as #Wiktor has done in a comment. This is simply a demonstration of a way to use a regular expression with an enumerator.
str = "set description \"alas-cd002-ak\""
enum = ['<desc>', '</desc>'].cycle
#=> #<Enumerator: ["<desc>", "</desc>"]:cycle>
str.gsub('"') { enum.next }
#=> "set description <desc>alas-cd002-ak</desc>"
Note: puts str displays
set description "alas-cd002-ak"

Related

regular expression extract words from file

I try to extract words from the string content like
export {AbcClient} from ...
export {AdcClient} from ..
How to use regular expression to get array of string? In this example is[AbcClient, AdcClient]
Thanks
Most programming languages have the ability to do a regex find all. In Python, we can try:
inp = """export {AbcClient} from ...
export {AdcClient} from .."""
matches = re.findall(r'\bexport \{(.*?)\}', inp)
print(matches)
This prints:
['AbcClient', 'AdcClient']

Refactoring - Replace all Fieldnames Starting with "_"

I'm about to refactor my project and I'd like to replace all variable names that start with "_" e.g. private final String _name; -> private final String name;
My Template fo FIND the Variables is simply:
$FieldName$
I set this regex for the variable name:
[_][a-z]+
Well, But this will just return a list of my variables starting with "_", how do I strip the _ and then set the new variable name?
EDIT: I edited this topic so maybe Eclipse users can tell me how to solve this with Eclipse.
The following works for me when using IntelliJ IDEA's Structural Search and Replace
Using your Search template, use the following Replacement template:
$NewName$
With Script text:
// FieldName refers to the Search template variable
if (FieldName instanceof com.intellij.psi.PsiVariable) {
com.intellij.psi.PsiVariable var = (com.intellij.psi.PsiVariable) FieldName;
var.getName().substring(1);
} else {
String string = FieldName.getText();
int index = string.indexOf('_');
string.substring(0, index) + string.substring(index + 1);
}
You can do this on a text basis via regular expressions in IntelliJ
Hit ctrl-shift-r to open "Replace in Path". Ensure Regular Expression is ticked, and enter the following:
Text to find: ([_])([a-zA-Z]+)
Replace with: $2
Beware, a possible issue here is that other text strings (e.g. EXIT_ON_CLOSE) might also be picked up by the regular expression, and you might have to be careful not to apply the replace in those cases (or adjust your regular expression to be smarter).

Find & Replace with a wildcard in Xcode 4

I'm trying to find all instances of text inside "" marks with a semi-colon directly after them, and replace the text inside the "" marks. So, for example:
"FirstKey" = "First value";
"SecondKey" = "Second value";
"ThirdKey" = "Third value";
Would find only those values after the equals signs, and could replace them all (with a single string) at once, like so:
"FirstKey" = "BLAH";
"SecondKey" = "BLAH";
"ThirdKey" = "BLAH";
How can I do this? I found some stuff referring to regular expressions in Xcode 3, but such functionality seems either gone or hidden in Xcode 4.
Regular expression replace is still available in Xcode 4. Use "Replace" and set style to "Regular Expression", use "([^"]*)"; as pattern and replace with "BLAH";.

looking for a regular expression to extract all text outputs to user from js file

i have some huge js files and there are some texts/messages/... which are output for a human beeing. the problem is they don't run over the same method.
but i want to find them all to refactor the code.
now i am searching for a regular expression to find those messages.
...his.submit_register = function(){
if(!this.agb_accept.checked) {
out_message("This is a Messge tot the User in English." , "And the Title of the Box. In English as well");
return fals;
}
this.valida...
what i want to find is all the strings which are not source code.
in this case i want as return:
This is a Messge tot the User in
English. And the Title of the Box. In
English as well
i tried something like: /\"(\S+\s{1})+\S\"/, but this wont work ...
thanks for help
It's not possible to parse Javascript source code using regular expressions because Javascript is not a regular language. You can write a regular expression that works most of the time:
/"(.*?)"/
The ? means that the match is not greedy.
Note: this will not correctly handle strings that contain ecaped quotes.
A simple java regex solving your problem (assuming that the message doesn't contain a " character):
Pattern p = Pattern.compile("\"(.+?)\"");
The extraction code :
Matcher m;
for(String line : lines) {
m = p.matcher(line);
while(m.find()) {
System.out.println(m.group(1));
}
}

regex to strip out image urls?

I need to separate out a bunch of image urls from a document in which the images are associated with names like this:
bellpepper = "http://images.com/bellpepper.jpg"
cabbage = "http://images.com/cabbage.jpg"
lettuce = "http://images.com/lettuce.jpg"
pumpkin = "http://images.com/pumpkin.jpg"
I assume I can detect the start of a link with:
/http:[^ ,]+/i
But how can I get all of the links separated from the document?
EDIT: To clarify the question: I just want to strip out the URLs from the file minus the variable name, equals sign and double quotes so I have a new file that is just a list of URLs, one per line.
Try this...
(http://)([a-zA-Z0-9\/\\.])*
If the format is constant, then this should work (python):
import re
s = """bellpepper = "http://images.com/bellpepper.jpg" (...) """
re.findall("\"(http://.+?)\"", s)
Note: this is not "find an image in a file" regexp, just an answer to the question :)
do you mean to say you have that kind of format in your document and you just want to get the http part? you can just split on the "=" delimiter without regex
$f = fopen("file","r");
if ($f){
while( !feof($f) ){
$line = fgets($f,4096);
$s = explode(" = ",$line);
$s = preg_replace("/\"/","",$s);
print $s[1];
}
fclose($f);
}
on the command line :
#php5 myscript.php > newfile.ext
if you are using other languages other than PHP, there are similar string splitting method you can use. eg Python/Perl's split(). please read your doc to find out
You may try this, if your tool supports positive lookbehind:
/(?<=")[^"\n]+/