flutter check if string starts with RegExp - regex

in flutter if we want to check if a string starts with a specific character...we can achieve that by:
var string = 'Dart';
string.startsWith('D'); // true
what if we want to check if the given string starts with multiple characters....i want to achieve this behaviour:
RegExp myRegExp = ('a-zA-Z0-9');
var string = 'Dart';
string.startsWith('D' + myRegExp);
is the above code is right?!!
my goal is to check if the string starts with a letter i specify...then a RegExp....
not to check if the string starts with 'D' only and thats it...

what if we want to check if the given string starts with multiple characters....i want to achieve this behaviour:
RegExp myRegExp = ('a-zA-Z0-9');
var string = 'Dart';
string.startsWith('D' + myRegExp);
That won't work. 'D' is a String object, and myRegExp presumably is intended to be a RegExp object. (Your syntax isn't correct; you probably want RegExp myRegExp = RegExp('[a-zA-Z0-9]');.) Both String and RegExp derive from a Pattern base class, but Pattern does not provide operator+, and String.operator+ works only with other Strings. Conceptually it's unclear what adding a String and RegExp should do; return a String? Return a RegExp?
You instead should just write a regular expression that accounts for your first character:
RegExp myRegExp = RegExp('D[a-zA-Z0-9]');
However, if you want the first character to be variable, then you can't bake it into the string literal used for the RegExp's pattern.
You instead could match the two parts separately:
var prefix = 'D';
var restRegExp = RegExp(r'[a-zA-Z0-9]');
var string = 'Dart';
var startsWith =
string.startsWith(prefix) &&
string.substring(prefix.length).startsWith(restRegExp);
Alternatively you could build the regular expression dynamically:
var prefix = 'D';
var restPattern = r'[a-zA-Z0-9]';
// Escape the prefix in case it contains any special regular expression
// characters. This is particularly important if the prefix comes from user
// input.
var myRegExp = RegExp(RegExp.escape(prefix) + restPattern);
var string = 'Dart';
var startsWith = string.startsWith(myRegExp);

I think you'll want something like string.startsWith(RegExp('D' + '[a-zA-Z0-9]'));

Related

Jest cell name won't recognise regex [duplicate]

I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps

What is the use of having a g at the end of the regex in javascript?

I am using a regex in jquery to filter only numbers.
var regex = /^[0-9]*$/
What is the difference between the above and /^[0-9]*$/g
It is one of the regular expression flags, which means global search, matched all the result in text.
Your question is the difference between the /^[0-9]*$/ and /^[0-9]*$/g
There is no difference in this specific case, because you want to filter only numbers, so whether you use flag 'g' or not, it would scan the whole string, return false if it has other characters.
But I can show you the difference between using flag 'g' or not in other case, like this:
var str = "abcdefgabcdefg";
var reg1 = /abcd/;
var reg2 = /abcd/g;
str.match(reg1); //output is ["abcd"]
str.match(reg2); //output is ["abcd", "abcd"]
There are some others flags like m, i, y. You can find the document here
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).
var str = "Is this all there is?";
var patt1 = /is/g;
var result = str.match(patt1);
Output:
is,is
Note: Is this all there is?
It will avoid first 'Is'.

Removing data from string using regular expressions in C Sharp

Definitely I'm not good using regular expressions but are really cool!, Now I want to be able to get only the name "table" in this string:
[schema].[table]
I want to remove the schema name, the square brackets and the dot.
so I will get only the work table
I tried this:
string output = Regex.Replace(reader["Name"].ToString(), #"[\[\.\]]", "");
So you came up with a new idea?? Here is what you can try:
string input = "[schema].[table]";
// replacing the first thing into [] with the dot with empty
string one = Regex.Replace(input, #"^\[.*?\]\.", "");
// or replacing anything before the dot with empty
// string two = Regex.Replace(input, #".*[.]", "");
try this
string strRegex = #"^\[.*?\]\.";
Regex myRegex = new Regex(strRegex, RegexOptions.None);
string strTargetString = #"[schema].[table]";
string strReplace = #"";
var result=myRegex.Replace(strTargetString, strReplace);
Console.WriteLine(result);
Why do you want to do replace if you just want to extract part of string?
string table = Regex.Match("[schema].[table]", #"\w+(?=]$)").Value;
It works even in case if you don't have schema.

AS3 Replace section of string with a dash using RegExp

I would like to be able to replace a section of a string with a dash. The section being replaced will be variable.
var str:String = "permanentContainer-temporaryContainer-"
var test:String = "temp";
var pattern:RegExp = /-[(+test+)]+-/i;
trace( str.replace(pattern,"-"));
I would like the result to trace:
permanentContainer--oraryContainer-
var str:String = "permanentContainer-temporaryContainer-"
var test:String ="temp";
var regex:RegExp = new RegExp(test,"ig");
trace(str.replace(regex,"-"));
If the variable test String you are replacing doesn't use special regex matching, then simple string functions would probably be more efficient (toLowerCase achieves case insensitive match, equivalent to regex "i" option):
var str:String = "permanentContainer-temporaryContainer-";
var test:String = "temp";
var idx:int = str.toLowerCase().indexOf(test.toLowerCase());
str = str.substr(0, idx)+'-'+str.substr(idx+test.length);
trace(str);
If you want to replace all instances of the test string (equivalent to regex "g" option):
var str:String = "permanentContainer-temporaryContainer-";
var test:String = "temp";
var idx:int = str.toLowerCase().indexOf(test.toLowerCase());
while (idx>=0) {
str = str.substr(0, idx)+'-'+str.substr(idx+test.length);
trace(str);
idx = str.toLowerCase().indexOf(test.toLowerCase());
}
I tested the performance of substr vs the RegEx, and it's very close, but it turns out that the RegEx is faster (on my platform) when you start adding options like case insensitivity and global replace (via the power of native implementations), though the string approach can be optimized (i.e. calling toLowerCase only once pre-loop, or substr search starting from the last matched idx.)

String parsing with RegExp in Actionscript

I have a string that is similar to a path, but I have tried some regex patterns that are supposed to parse paths and they don't quite work.
Here's the string
f|MyApparel/Templates/Events/
I need the "name parts" between the slashes.
I tried (\w+) but the array came back [0] = "f" and [1] = "f".
I tested the pattern on http://www.gskinner.com/RegExr/ and it seems to work correctly.
Here's the AS code:
var pattern : RegExp = /(\w+)/g;
var hierarchy : Array = pattern.exec(params.category_id);
params.name = hierarchy.pop() as String;
pattern.exec() works like in JavaScript. It resets the lastIndex property every time it finds a match for a global regex, and next time you run it it starts from there.
So it does not return an array of all matches, but only the very next match in the string. Hence you must run it in a loop until it returns null:
var myPattern:RegExp = /(\w+)/g;
var str:String = "f|MyApparel/Templates/Events/";
var result:Object = myPattern.exec(str);
while (result != null) {
trace( result.index, "\t", result);
result = myPattern.exec(str);
}
I don't know between which two slashes you want but try
var hierarchy : Array = params.category_id.split(/[\/|]/);
[\/|] means a slash or a vertical bar.