I need to input a String that is basically a membership number.
It has to contain two letters in the beginning followed by four numbers.
For example, AA1111 or AB1234.
How can I validate that the first two digits are letters and the last four digits are integers?
In c#:
public void validate()
{
string input = textBox1.Text;
var re = "^[a-zA-Z]{2}[0-9]{4}$";
if (Regex.IsMatch(input, re))
{
MessageBox.Show("true");
}
else
{
MessageBox.Show("false");
}
}
In javaScripts:
function validate()
{
var input = document.getElementById("Text1").value;
var re = new RegExp(/^[a-zA-Z]{2}[0-9]{4}$/);
if (re.test(input))
{
alert("true");
}
else
{
alert("false");
}
}
If we split regular expression, it validates input string in start and end
^[a-zA-Z]{2}-----------------------------------------[0-9]{4}$
First two character must be alphabets
^ =*from start*
[a-zA-Z] =*lower and upper case alpha*
{2} =*Exactly two character*
Last four characters must be digits
[0-9] =*digits*
{4} =*exactly four charater*
$ =*at end*
Related
I want to split a string of emojis into each emoji. so how can I do this in dart language?
void main() {
print('GoodJob'.split("")); // output: [G, o, o, d, J, o, b]
print('π€π±π'.split("")); // output: [οΏ½, οΏ½, οΏ½, οΏ½, οΏ½, οΏ½] but expected: ['π€','π±','π']
}
Docs from TextField recommends to use characters package to work with emoji in dart.
Docs describe as follows,
It's important to always use characters when dealing with user input text that may contain complex characters. This will ensure that extended grapheme clusters and surrogate pairs are treated as single characters, as they appear to the user.
For example, when finding the length of some user input, use string.characters.length. Do NOT use string.length or even string.runes.length. For the complex character "π¨βπ©βπ¦", this appears to the user as a single character, and string.characters.length intuitively returns 1. On the other hand, string.length returns 8, and string.runes.length returns 5!
import 'package:characters/characters.dart';
void main() {
print('π€π±π'.characters.split("".characters));
}
outputs
(π€, π±, π)
You can match all the emojis using regex, and then add them to a list:
List<String> splitEmoji(String text) {
final List<String> out = [];
final pattern = RegExp(
r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])');
final matches = pattern.allMatches(text);
for (final match in matches) {
out.add(match.group(0)!);
}
return out;
}
Regex credit
Usage:
print(splitEmoji('π€π±π')); // Output: [π€, π±, π]
You can use the runes property of String.
void main() {
final String emojis = 'π€π±π';
final Runes codePoints = emojis.runes;
for (final codePoint in codePoints) {
print(String.fromCharCode(codePoint));
}
}
if my string is lets say "Alfa1234Beta"
how can I convert all the number in to "_"
for example "Alfa1234Beta"
will be "Alfa____Beta"
Going with the Regex approach pointed out by others is possibly OK for your scenario. Mind you however, that Regex sometimes tend to be overused. A hand rolled approach could be like this:
static string ReplaceDigits(string str)
{
StringBuilder sb = null;
for (int i = 0; i < str.Length; i++)
{
if (Char.IsDigit(str[i]))
{
if (sb == null)
{
// Seen a digit, allocate StringBuilder, copy non-digits we might have skipped over so far.
sb = new StringBuilder();
if (i > 0)
{
sb.Append(str, 0, i);
}
}
// Replace current character (a digit)
sb.Append('_');
}
else
{
if (sb != null)
{
// Seen some digits (being replaced) already. Collect non-digits as well.
sb.Append(str[i]);
}
}
}
if (sb != null)
{
return sb.ToString();
}
return str;
}
It is more light weight than Regex and only allocates when there is actually something to do (replace). So, go ahead use the Regex version if you like. If you figure out during profiling that is too heavy weight, you can use something like the above. YMMV
You can run for loop on the string and then use the following method to replace numbers with _
if (!System.Text.RegularExpressions.Regex.IsMatch(i, "^[0-9]*$"))
Here variable i is the character in the for loop .
You can use this:
var s = "Alfa1234Beta";
var s2 = System.Text.RegularExpressions.Regex.Replace(s, "[0-9]", "_");
s2 now contains "Alfa____Beta".
Explanation: the regex [0-9] matches any digit from 0 to 9 (inclusive). The Regex.Replace then replaces all matched characters with an "_".
EDIT
And if you want it a bit shorter AND also match non-latin digits, use \d as a regex:
var s = "Alfa1234BetaΰΉ"; // ΰΉ is "Thai digit three"
var s2 = System.Text.RegularExpressions.Regex.Replace(s, #"\d", "_");
s2 now contains "Alfa____Beta_".
I have a string that starts with 7 characters (let's say XXXXXXX) and after that there are 8 characters that represnet a decimal number.
For example: XXXXXXX30.00000 would be 30.00 (I want 2 decimal places)
So it should start on index 7 read until dot (.) + 2 decimal places. It should be a string, not a number. I tried with string.substring() but got stuck here.
First you can remove the first 7 characters by
var newString = yourString.removeRange(0,6)
then you can cast to a double if you're certain it will always be a number
var yourNumber = newString.ToDouble()
If you're not sure you can wrap in a try/catch eg:
try{
var yourNumber = newString.ToDouble()
}catch(e:TypeCastException){
println("Failed to cast to double - "+ e.message)
}
additionally, to round to a 2 decimal places:
val number2digits:Double = String.format("%.2f", yourNumber).toDouble()
I suggest you do it using the regex, [A-Za-z]{8}(\d+.\d{2})
Explanation of the regex:
[A-Za-z]{8} specifies 8 characters. If you want to support characters other than English alphabets, you can replace [A-Za-z] with \p{L} which specifies unicode letters.
(\d+.\d{2}) specifies a capturing group consisting of digits followed by . which in turn should be followed by 2 digits as per your requirement. A regex pattern can have more than one capturing groups. Since it is the first capturing group in this pattern, it can be accessed by group(1).
A test code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
// Some test strings
String[] arr = { "abcdefgh30.00000", "abcdefgh300.0000", "abcdefgh3000.00", "abcdefgh3.00000",
"abcdefgh0.05000" };
Pattern pattern = Pattern.compile("[A-Za-z]{8}(\\d+.\\d{2})");
for (String s : arr) {
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
String str = matcher.group(1);
System.out.println(str);
}
}
}
}
Output:
30.00
300.00
3000.00
3.00
0.05
I like to find all words in a List string equal input word, but 2 characters has variation. I like to find all words equal:
xxxV1xxx;
xxxV2xxx;
xxxV3xxx;...
I do not care if the word include V1, V2, V3; but has to have the same characters before and after.
Use mystring.StartsWith("xxx") && mystring.EndsWith("xxx")
Here is an example:
string[] str = { "xxxv1xxx", "xxxV2xxx", "xxxv3xxx", "xxv4xx", "xxV5xxx"};
foreach (string s in str)
{
if( s.StartsWith("xxx") && s.EndsWith("xxx"))
Console.WriteLine(s); //do whatever you want here
}
Fiddle: https://dotnetfiddle.net/STnyWE
I'm stuck on a task of trying to print words that contain only lowercase letters a-z. I have already stripped out an inputted string if it contains any number 0-9 and if it contains an Uppercase letter:
String[] textParts;
textParts = text.Split(delimChars);
for (int i = 0; i < textParts.Length; i++) //adds s to words list and checks for capitals
{
String s = textParts[i];
bool valid = true;
foreach (char c in textParts[i])
{
if (char.IsUpper(c))
{
valid = false;
break;
}
if (c >= '0' && c <= '9')
{
valid = false;
break;
}
if (char.IsPunctuation(c))
{
valid = false;
break;
}
}
if (valid) pageIn.words.Add(s);
This is my code so far. The last part I'm trying to check to see if a word contains any punctuation (it's not working) is there an easier way I could do this and how could I get the last part of my code to work?
P.S. I'm not that comfortable with using Regex.
Many Thanks,
Ellie
Without regex, you can use LINQ (might be less performant)
bool isOnlyLower = s.Count(c => Char.IsLower(c)) == s.Length;
Count will retrieve the number of char that are in lower in the following string. If it match the string's length, string is composed only of lowercase letters.
An alternative would be to check if there's any UpperCase :
bool isOnlyLower = !s.Any(c => Char.IsUpper(c));
var regex = new Regex("^[a-z]+$");
if (!regex.IsMatch(input))
{
// is't not only lower case letters, remove input
}
I'm not sure whether I get your question right, but shouldn't the following work?
for (int i = 0; i < textParts.Length; i++) //adds s to words list and checks for capitals
{
String s = textParts[i];
if(s.Equals(s.ToLower()))
{
// string is all lower
}
}