I want to check input string is in correct format. ^[\d-.]+$ expression check only existance of numbers and .(dot) and -(minus) But I want to check its sequence also.
Suppose I want to use calculator with . and - only. How to get regular expression which satify below all conditions.
Regex.IsMatch(input, #"^[\d-\.]+$")
//this expression works for below conditions only
if string v1="10-20-30"; // should return true
if string v1="10-20"; // should return true
if string v1="10.20"; // should return true
if string v1="10R20"; // should return false
if string v1="10#20"; // should return false
if string v1="10-20.30.40-50"; // should return true
if string v1="10"; // should return true
//above expression not works for below conditions
if string v1="10--20.30"; // should return false
if string v1="10-20-30.."; // should return false
if string v1="--10-20.30"; // should return false
if string v1="-10-20.30"; // should return false
if string v1="10-20.30."; // should return false
So something like
var pattern = #"^(\d+(-|\.))*\d+$";
should do the job for you.
What this regex "is saying" is:
Find one or more digits (\d+)
Followed by a minus sign or dot (-|.) - need to escape the dot here with \
This could be 0 or more times in the string - the star sign in the end (\d+(-|.))*
And then another one or more digits (\d+).
All this should be right after the beginning of the string and right before the end (the ^ and $ I believe you know about).
Note: If you need to be possible the numbers to be negative, you will need to add another conditional minus sign before both \d+ instances in the regex or :
var pattern = #"^(-?\d+(-|.))*-?\d+$";
Regards
Related
I have a scenario where i want to extract some substring based on following condition.
search for any pattern myvalue=123& , extract myvalue=123
If the "myvalue" present at end of the line without "&", extract myvalue=123
for ex:
The string is abcdmyvalue=123&xyz => the it should return myvalue=123
The string is abcdmyvalue=123 => the it should return myvalue=123
for first scenario it is working for me with following regex - myvalue=(.?(?=[&,""]))
I am looking for how to modify this regex to include my second scenario as well. I am using https://regex101.com/ to test this.
Thanks in Advace!
Some notes about the pattern that you tried
if you want to only match, you can omit the capture group
e* matches 0+ times an e char
the part .*?(?=[&,""]) matches as least chars until it can assert eiter & , or " to the right, so the positive lookahead expects a single char to the right to be present
You could shorten the pattern to a match only, using a negated character class that matches 0+ times any character except a whitespace char or &
myvalue=[^&\s]*
Regex demo
function regex(data) {
var test = data.match(/=(.*)&/);
if (test === null) {
return data.split('=')[1]
} else {
return test[1]
}
}
console.log(regex('abcdmyvalue=123&3e')); //123
console.log(regex('abcdmyvalue=123')); //123
here is your working code if there is no & at end of string it will have null and will go else block there we can simply split the string and get the value, If & is present at the end of string then regex will simply extract the value between = and &
if you want to use existing regex then you can do it like that
var test = data1.match(/=(.*)&|=(.*)/)
const result = test[1] ? test[1] : test[2];
console.log(result);
I have a string that sometimes contains a certain substring at the end and sometimes does not. When the string is present I want to update its value. When it is absent I want to add it at the end of the existing string.
For example:
int _newCount = 7;
_myString = 'The count is: COUNT=1;'
_myString2 = 'The count is: '
_rRuleString.replaceAllMapped(RegExp('COUNT=(.*?)\;'), (match) {
//if there is a match (like in _myString) update the count to value of _newCount
//if there is no match (like in _myString2) add COUNT=1; to the string
}
I have tried using a return of:
return "${match.group(1).isEmpty ? _myString + ;COUNT=1;' : 'COUNT=$_newCount;'}";
But it is not working.
Note that replaceAllMatched will only perform a replacement if there is a match, else, there will be no replacement (insertion is still a replacement of an empty string with some string).
Your expected matches are always at the end of the string, and you may leverage this in your current code. You need a regex that optionally matches COUNT= and then some text up to the first ; including the char and then checks if the current position is the end of string.
Then, just follow the logic: if Group 1 is matched, set the new count value, else, add the COUNT=1; string:
The regex is
(COUNT=[^;]*;)?$
See the regex demo.
Details
(COUNT=[^;]*;)? - an optional group 1: COUNT=, any 0 or more chars other than ; and then a ;
$ - end of string.
Dart code:
_myString.replaceFirstMapped(RegExp(r'(COUNT=[^;]*;)?$'), (match) {
return match.group(0).isEmpty ? "COUNT=1;" : "COUNT=$_newCount;" ; }
)
Note the use of replaceFirstMatched, you need to replace only the first match.
I have regexp code like below (I'm using VerbalExpression dart plugin ), My purpose is to check that a string starts with "36", followed by "01", "02", or "03". After that can be anything as long as the whole string is 16 characters long.
var regex = VerbalExpression()
..startOfLine()
..then("36")
..then("01")
..or("02")
..anythingBut(" ")
..endOfLine();
String nik1 = "3601999999999999";
String nik2 = "3602999999999999";
String nik3 = "3603999999999999";
print('result : ${regex.hasMatch(nik1)}');
print('Hasil : ${regex.hasMatch(nik2)}');
print('Hasil : ${regex.hasMatch(nik3)}');
my code only true for nik1 and nik2, however i want true for nik3, I noticed that i can't put or() after or() for multiple check, it just give me all false result, how do i achieve that?
I'm not familiar with VerbalExpression, but a RegExp that does this is straightforward enough.
const pattern = r'^36(01|02|03)\S{12}$';
void main() {
final regex = RegExp(pattern);
print(regex.hasMatch('3601999999999999')); // true
print(regex.hasMatch('3602999999999999')); // true
print(regex.hasMatch('3603999999999999')); // true
print(regex.hasMatch('360199999999999')); // false
print(regex.hasMatch('3600999999999999')); // false
print(regex.hasMatch('36019999999999999')); // false
}
Pattern explanation:
The r prefix means dart will interpret it as a raw string ("$" and "\" are not treated as special).
The ^ and $ represent the beginning and end of the string, so it will only match the whole string and cannot find matches from just part of the string.
(01|02|03) "01" or "02" or "03". | means OR. Wrapping it in parentheses lets it know where to stop the OR.
\S matches any non-whitespace character.
{12} means the previous thing must be repeated 12 times, so \S{12} means any 12 non-whitespace characters.
I have to pass a string into a program, depending on the string, it will return only one response value. I am facing difficulty in building patterns for two cases.
If a string ends with '?' and is not all uppercase return 'x', no matter what the contents of string.
If a string end with '?' and is all uppercase return 'y'.
If a string ends with '!' , or is all uppercase (no question mark at end) return 'z'.
If a string is only whitespace return 'a'.
Here are two example strings, they are to be four separate patterns -
phrase1 = "Simple String with some UPPercase in Between ends with?"
phrase2 = "BIG STRING ALL CAPS ENDS WITH?"
phrase3_a = "ALLCAPSSTRING NOTHING AT THE END OF STRING"
phrase3_b = "Any String with ALL UPPERCASE (or not) but ends with!"
phrase4 = "\t\t\t\t"
I haven't built accurate patterns, and that's what I'm asking here. After that I plan to use a single re.compile with all patterns & then finditer to use the group which is not None. In code below, I have removed the whitespaces,since if none of the other patterns match, matching a whitespace pattern [\s] will return None, which I can use separetely-
phrase=re.sub(r'[\s]','',phrase)
pattern_phrase1 = re.compile (r'[a-zA-Z0-9]\?$')
pattern_phrase2 = re.compile (r'[A-Z0-9]\?$')
pattern_phrase3 = re.compile (r'[A-Z]|[.!$]')
Solution 1 - using isx functions
def hey(phrase):
responses ={'ques':x,'ques_yell':y,'yell':z,'onlycall':b,'what':c}
phrase=''.join(phrase.split())
if phrase=='':
return responses['onlycall']
if phrase.isupper():
if phrase[-1]=='?':
return responses['ques_yell']
return responses['yell']
elif not phrase.isupper():
if phrase[-1]=='?':
return responses['ques']
return responses['what']
why this function will return "e10" as true? (which is supposed to be false)
public boolean isNumber(String s) {
String pattern = "\\s*[+-]?((\\d+.?\\d*)|.\\d+)(e[+-]?\\d+)?\\s*";
return s.matches(pattern);
}
Because of ((\\d+.?\\d*)|.\\d+). The second part means . - a matcher for anything, and \d+ - at least one digit.
If you meant to match an actual dot character, use \. instead.