How to get Boolean variable in Regular expressions Swift 4 [duplicate] - regex

This question already has answers here:
How to validate an e-mail address in swift?
(39 answers)
Closed 5 years ago.
I'm trying to make a regular expression that looks for an e-mail. Everything works . How to get a Bool variable that would mean whether such an expression was found or not?
let someString = "123milka#yandex.ru123"
let regexp = "([a-zA-Z]{1,20})#([a-zA-Z]{1,20}).(com|ru|org)"
if let range = someString.range(of: regexp, options: .regularExpression) {
let result : String = someString.substring(with: range)
print(result)
}

You already have an if test, so use that, setting your Boolean as you see fit. There are tons of ways of doing that, e.g.:
let success: Bool
if let range = someString.range(of: regexp, options: .regularExpression) {
success = true
let result = someString.substring(with: range)
print(result)
} else {
success = false
}

Related

Get the number between two characters - Typescript [duplicate]

This question already has answers here:
RegExp in TypeScript
(5 answers)
Closed 2 years ago.
I am new to Typescript and trying to make a webhook in my Google Cloud Functions.
I have a string: C1234567890A460450P10TS1596575969702
I want to use regex to extract the number 1234567890 from that string.
The first character C is fixed and does not change, the character A after the number is variable and can be any other alphabet.
The regex that matches the number is (?<=C)(\d{10})(?=\w).
I want to know how to execute this regex in Typescript so that I can get the number into a variable(eg: const number = [the number extracted from the string] //value 1234567890)
Edit 1:
Based on the provided suggestions (which I had tried already before posting this question), here is the code I could make out of it:
const string = request.body.string;
let regxp = new RegExp('(?<=C)(\d{10})(?=\w)');
const number = regxp.exec(string);
response.send(number);
This gives a blank response.
There is two problems, you never parsed the returned string to a number with parseInt and (?<=C) (positive lookbehind) is not always supported.
Second, your regular expression can be simplified into ^C\d{10} and a .splice(1) to remove the C.
const string: string = request.body.string;
const matches = s.match(/^C\d{10}/);
let number: number;
if(matches !== null) {
number = parseInt(matches[0].slice(1));
} else {
res.status(400).end(); // Assuming this is express
return;
}
res.send(number); // 1234567890
Playground

Why my regEx does not work in JScript? [duplicate]

This question already has answers here:
Differences between Javascript regexp literal and constructor
(2 answers)
Javascript RegEx Not Working [duplicate]
(1 answer)
Closed 4 years ago.
I have the following RegEx that works well in Java Script but not in JScript. The only difference I found between the 2 is the that JScript uses /expression/ and tried it with no luck. I need to match specific string date format.
var pattern = "/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))T(00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$/";
var regexpattern = new RegExp(pattern);
var str = "2018-02-28T17:05:10";
var res = regexpattern.test(str);
//var res = str.match(pattern);
if ( res != null)
{
Log.Message("Test worked ");
}
else
{
Log.Message("did not");
}
EDIT:
It should be declared as:
var pattern = /([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))T(00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$/;

Regex match in string [duplicate]

This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I would like to extract two numbers for a strings by regex "[0-9]+"
var str = "ABcDEFG12345DiFKGLSG938SDsFSd"
What I want to extract is "12345" and "938".
But I am not sure how to do so in Kotlin.
This should work:
import java.util.regex.Matcher
import java.util.regex.Pattern
fun main(args:Array<String>) {
val p = Pattern.compile("\\d+")
val m = p.matcher("ABcDEFG12345DiFKGLSG938SDsFSd")
while (m.find())
{
println(m.group())
}
}
Pattern.compile("\\d+"), it will extract the digits from the expression.

Regex Issue in Swift [duplicate]

This question already has answers here:
Match exact string
(3 answers)
Closed 6 years ago.
I am working on a username regex where the only characters that are accepted are a-z, A-Z, 0-9, and _. The current max length of the username is 18 characters with a minimum of one. My current regex is below.
let regexCorrectPattern = "[a-zA-Z0-9_]{1,18}$"
I am having the following issue. Special characters added anywhere but the end of the string allow the regex to pass. For example
jon! FAIL
!jon PASS
j!on PASS
The method I am using to test the regex is below along with the calling method. Any input would be greatly appreciated.
Regex Testing Method
func regexTestString(string: String, withPattern regexPattern: String) -> Bool
{
// This method is used for all of the methods below.
do
{
// Create regex and regex range.
let regex = try NSRegularExpression(pattern: regexPattern, options: .CaseInsensitive)
let range = NSMakeRange(0, string.characters.count)
// Test for the number of regex matches.
let numberOfMatches = regex.numberOfMatchesInString(string, options: [], range: range)
// Testing Code.
print(numberOfMatches)
// Return true if the number of matches is greater than 1 and return false if the number of mathces is 0.
return (numberOfMatches == 0) ? false : true
}
catch
{
// Testing Code
print("There is an error in the SignUpViewController regexTestString() method \(error)")
// If there is an error return false.
return false
}
}
Calling Method
func usernameTextFieldDidEndEditing(sender: AnyObject)
{
let usernameText = self.usernameField.text!.lowercaseString
let regexCorrectPattern = "[a-zA-Z0-9_]{1,18}$"
let regexWhitespacePattern = "\\s"
let regexSpecialCharacterPattern = ".*[^A-Za-z0-9].*"
if regexTestString(usernameText, withPattern: regexCorrectPattern)
{
// The regex has passed hide the regexNotificationView
}
else if regexTestString(usernameText, withPattern: regexWhitespacePattern)
{
// The username contains whitespace characters. Alert the user.
}
else if regexTestString(usernameText, withPattern: regexSpecialCharacterPattern)
{
// The username contains special characters. Alert the user.
}
else if usernameText == ""
{
// The usernameField is empty. Make sure the sign up button is disabled.
}
else
{
// For some reason the Regex is false. Disable the sign up button.
}
}
You want the entire string to contain only the characters you specified, so all you need is to add ^ at the start of the pattern:
^[a-zA-Z0-9_]{1,18}$

Typescript: How to write long regexp in 2 lines [duplicate]

This question already has answers here:
How to split a long regular expression into multiple lines in JavaScript?
(11 answers)
Closed 7 years ago.
I use tslint and when I write long regexp in typescript
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
I got error - exceeds maximum line length of 140.
Does anybody know how to write it in 2 lines. I can do that with a hack. But I'm not satisfied with this solution.
var r1 = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))/;
var r2 = /#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var re = new RegExp(r1.source + r2.source);
Why not use strings?
var r1 = "^(([^<>()\[\]\\.,;:\s#\"]+(\.[^<>()\[\]\\.,;:\s#\"]+)*)|(\".+\"))";
var r2 = "#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$";
var re = new RegExp(r1 + r2);
RegExp(string) is easier for modification and/or dynamically generated regex