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).
Related
Let's say I have two elements with these texts: "Find a hero" and "Find the hero".
I want to use cy.contains() to find one of these, and want to write something like
cy.contains("Find" + * + "hero")
I don't understand how I can write this command to find anything that contains the two words "Find" and "hero" in a sentence, no matter the order or where they come in.
I'm only using the native cypress (no imported testing libraries, was hoping it won't be necessary).
Hope someone can help.
The format of .contains() to use is a regex parameter, which has "/" delimiters:
cy.contains(/Find .* hero/)
The ".*" in the middle means any characters, and any number of characters.
Check out the example on https://regex101.com.
It's possible to use startsWith and endsWith
cy.get(selector)
.should('satisfy', ($el) => {
const text = $el.text()
return text.startsWith('Find') && text.endsWith('hero')
})
This is my helper function
const contain = ($el, first, last) => {
const text = $el.text()
return text.startsWith(first) && text.endsWith(last)
}
cy.get(selector)
.should($el => contain($el, 'Find', 'hero'))
Double contains
I don't think anyone mentioned yet, you can use :contains() inside .contains()
cy.contains(':contains(Find)', 'hero') // both strings contained
Matches the 2nd one:
<div>Find the villain</div>
<div>Find the hero</div>
You could use a regex expression to assert that text contain both 'Find' and 'Hero' by doing the following :
cy.get('[data-cy=login-button]').invoke('text').should('match', new RegExp('.*Find.*hero', 'gi'));
Or your could even do
cy.get('YOUR_ELEMENT').should('contains', 'Find').should('contains', 'Hero')
I am trying to search in a string for a certain value and replace it with another value.
The example:
String: "/accounts/{accountId}/cheques/{chequeId}/cancel"
I am trying to replace anything between { and } with the number 1.
So I would end up with:
String: "/accounts/1/cheques/1/cancel"
I am using the following:
prepedURI = System.Text.RegularExpressions.Regex.Replace(prepedURI, "{.*}", "1")
But unfortunately, the Replace function is returning:
String: "/accounts/1/cancel"
It seems to be ignoring the first } and replacing everything up to the 2nd }.
Any advice?
Excuse my dumb. This is my first Regex experience, and I am trying my best to understand all these 'flags' in the pattern.
Example (you can paste into a button click event to see what I mean):
Dim prepedURI As String = "/accounts/{accountId}/cheques/{chequeId}/cancel"
prepedURI = System.Text.RegularExpressions.Regex.Replace(prepedURI, "{.*}", "1")
MsgBox(prepedURI)
Use ? before the closing curly brace
{.*?}
Working example can be found at the following link -
http://rubular.com/r/1LpnGNC3sC
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";.
Using Actionscript 3.0 (Within Flash CS5)
A standard regex to match any digit is:
var myRegexPattern:Regex = /\d/g;
What would the regex look like to incorporate a string variable to match?
(this example is an 'IDEAL' not a 'WORKING' snippet) ie:
var myString:String = "MatchThisText"
var myRegexPatter_WithString:Regex = /\d[myString]/g;
I've seen some workarounds which involve creating multiple regex instances, then combine them by source, with the variable in question, which seems wrong. OR using the flash string to regex creator, but it's just plain sloppy with all the double and triple escape sequences required.
There must be some pain free way that I can't find in the live docs or on google. Does AS3 hold this functionality even? If not, it really should.
Or I am missing a much easier means of simply avoiding this task that I'm simply naive too due to my newness to regex?
I've actually blogged about this, so I'll just point you there: http://tyleregeto.com/using-vars-in-regular-expressions-as3 It talks about the possible solutions, but there is no ideal one like you mention.
EDIT
Here is a copy of the important parts of that blog entry:
Here is a regex to strip the tags from a block of text.
/<("[^"]*"|'[^']*'|[^'">])*>/ig
This nifty expression works like a charm. But I wanted to update it so the developer could limit which tags it stripped to those specified in a array. Pretty straight forward stuff, to use a variable value in a regex you first need to build it as a string and then convert it. Something like the following:
var exp:String = 'start-exp' + someVar + 'more-exp';
var regex:Regexp = new RegExp(exp);
Pretty straight forward. So when approaching this small upgrade, that's what I did. Of course one big problem was pretty clear.
var exp:String = '/<' + tag + '("[^"]*"|'[^']*'|[^'">])*>/';
Guess what, invalid string! Better escape those quotes in the string. Whoops, that will break the regex! I was stumped. So I opened up the language reference to see what I could find. The "source" parameter, (which I've never used before,) caught my eye. It returns a String described as "the pattern portion of the regular expression." It did the trick perfectly. Here is the solution:
var start:Regexp = /])*>/ig;
var complete:RegExp = new RegExp(start.source + tag + end.source);
You can reduce it down to this for convenience:
var complete:RegExp = new RegExp(/])*>/.source + tag, 'ig');
As Tyler correctly points out (and his answer works just fine), you can assemble your regex as a string end then pass this string to the RegExp constructor with the new RegExp("pattern", "flags") syntax.
function assembleRegex(myString) {
var re = new RegExp('\\d' + myString, "i");
return re;
}
Note that when using a string to store a regex pattern, you do need to add some extra backslashes to get it to work right (e.g. to get a \d in the regex, you need to specify \\d in the string). Note also that the string pattern does not use the forward slash delimiters. In other words, the following two statements are equivalent:
var re1 = /\d/ig;
var re2 = new Regexp("\\d", "ig");
Additional note: You may need to process the myString variable to escape any backslashes it might contain (if they are to be interpreted as literal). If this is the case the function becomes:
function assembleRegex(myString) {
myString = myString.replace(/\\/, '\\\\');
var re = new RegExp('\\d' + myString);
return re;
}
Can anyone help me with a regex to turn:
filename_author
to
author_filename
I am using MS Word 2003 and am trying to do this with Word's Find-and-Replace. I've tried the use wildcards feature but haven't had any luck.
Am I only going to be able to do it programmatically?
Here is the regex:
([^_]*)_(.*)
And here is a C# example:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
String test = "filename_author";
String result = Regex.Replace(test, #"([^_]*)_(.*)", "$2_$1");
}
}
Here is a Python example:
from re import sub
test = "filename_author";
result = sub('([^_]*)_(.*)', r'\2_\1', test)
Edit: In order to do this in Microsoft Word using wildcards use this as a search string:
(<*>)_(<*>)
and replace with this:
\2_\1
Also, please see Add power to Word searches with regular expressions for an explanation of the syntax I have used above:
The asterisk (*) returns all the text in the word.
The less than and greater than symbols (< >) mark the start and end
of each word, respectively. They
ensure that the search returns a
single word.
The parentheses and the space between them divide the words into
distinct groups: (first word) (second
word). The parentheses also indicate
the order in which you want search to
evaluate each expression.
Here you go:
s/^([a-zA-Z]+)_([a-zA-Z]+)$/\2_\1/
Depending on the context, that might be a little greedy.
Search pattern:
([^_]+)_(.+)
Replacement pattern:
$2_$1
In .NET you could use ([^_]+)_([^_]+) as the regex and then $2_$1 as the substitution pattern, for this very specific type of case. If you need more than 2 parts it gets a lot more complicated.
Since you're in MS Word, you might try a non-programming approach. Highlight all of the text, select Table -> Convert -> Text to Table. Set the number of columns at 2. Choose Separate Text At, select the Other radio, and enter an _. That will give you a table. Switch the two columns. Then convert the table back to text using the _ again.
Or you could copy the whole thing to Excel, construct a formula to split and rejoin the text and then copy and paste that back to Word. Either would work.
In C# you could also do something like this.
string[] parts = "filename_author".Split('_');
return parts[1] + "_" + parts[0];
You asked about regex of course, but this might be a good alternative.