How to extract the first 3 free standing characters from a string? - c#

I have a program that needs to parse town names. Sometimes the user enters the correct town name but often the users enter the post code as the town name.
In case I cannot match the town name with a valid town name, I am assuming that the input contains the post code. The first 3 free standing characters of the post code uniquely identify the town.
Post codes have this format 3 letters followed by 3 digits, e.g. ABC123.
However some users enter the digits before the letters and some users combine the town name and the post code, e.g.
123ABC
Pretty city ABC123
How do I extract the first 3 free standing characters?
Free standing = to the left and right of the 3 characters are no other characters.
For the below strings ABC are the first 3 free standing characters.
ABC123
123ABC
ABC 123
123 ABC
123 ABC 456
ABC12DEF
123 ABC DEF
DE 123 ABC
Pretty city ABC123
These next strings do not have 3 free standing characters.
123ABCDEF
ABCD123
123ABCD
123 ABCD
Somename1234
1234Somename
Case is irrelevant.
Here are my attempts
Using regex. Does not work for "Pretty City ABC123"
Regex rgx = new Regex("[a-zA-Z]{3}");
string hamster = "ABC123";
var code = rgx.Match(hamster);
Awkward function
private static string GetCode(string pig)
{
var code = "";
var canstart = true;
for (int i = 0; i < pig.Length; i++)
{
//Console.WriteLine(code);
if (code.Length == 3)
{
if (char.IsLetter(pig[i]))
{
canstart = false;
code = "";
}
else
{
break;
}
}
if (char.IsLetter(pig[i]) && canstart)
{
code += pig[i];
}
else if (!char.IsLetter(pig[i]) && !canstart)
{
canstart = true;
}
}
if (code.Length != 3)
{
code = "";
}
return code;
}

You can use
(?<![a-zA-Z])[a-zA-Z]{3}(?![a-zA-Z])
See the regex demo. Details:
(?<![a-zA-Z]) - a negative lookbehind that matches a location that is not immediately preceded with an ASCII letter
[a-zA-Z]{3} - three ASCII letters
(?![a-zA-Z]) - a negative lookahead that matches a location that is not immediately followed with an ASCII letter.
In C#:
var rgx = new Regex(#"(?<![a-zA-Z])[a-zA-Z]{3}(?![a-zA-Z])");
var hamster = "ABC123";
var code = rgx.Match(hamster)?.Value;

Related

Validate String With Regex

I'm trying to validate a string with this regex
var regexAgencia = new Regex("^(?!0000)([0-9]{4})");
var result = regexAgencia.IsMatch(agencia);
Valid Options:
N-X
NN-X
NNN-X
NNNN-X
N
NN
NNN
NNNN
Invalid Options:
0-X
00-X
000-X
0000-X
0
00
000
0000
Where N is any number 0-9 and X can be X or 0-9
When I validade this "014777417" the regex return true
I need help to write a regex to validade this string with this rules.
This should do it for you:
^(?=\d*[1-9])\d{1,4}(?:-[X\d])?$
It starts with a positive look ahead to ensure a digit other than zero is present ((?=\d*[1-9])). Thereafter it matches 1-4 digits, optionally followed by a hyphen and a digit or X.
See it here at regex101.
You certainly can do this through just Regex, however, I always have this lingering fear of creating code that either:
1) only I understand or remember
2) even I don't understand when looking back
In that spirit, it seems if you do a simple split, your string might be easier to evaluate:
string[] parts = agencia.Split('-');
if ((parts.Length == 1 && Regex.IsMatch(agencia, #"^\d{1,4}$")) ||
(parts.Length == 2 && Regex.IsMatch(parts[0], #"^\d{1,4}$")) &&
Regex.IsMatch(parts[1], #"^[0-9X]$"))
{
}
-- EDIT --
I can't tell if you want 0 or not, so if you don't, change \d from to [1-9].
It would be easier to have two tests: one to check if it could be valid, followed by one to exclude the special case of all leading zeros being invalid:
static void Main(string[] args)
{
string[] agencias = { "", "1234-5", "0-9", "014777417", "0000", "1-23", "01-0", "1-234 abcd", "0123-4" };
var regexAgenciaValid = new Regex("^(([0-9]{1,4})(-[0-9])?)$");
var regexAgenciaInvalid = new Regex("^((0{1,4})(-[0-9])?)$");
foreach (string agencia in agencias)
{
var result = regexAgenciaValid.IsMatch(agencia) && !regexAgenciaInvalid.IsMatch(agencia);
Console.WriteLine(agencia + " " + result);
}
Console.ReadLine();
}
Output:
False
1234-5 True
0-9 False
014777417 False
0000 False
1-23 False
01-0 True
1-234 abcd False
0123-4 True
This has the bonus of being easier to modify in the future.

C# Regex Match Address - Mark groups optional

I need to parse a German address that I get in one string like "Example Street 5b". I want to split it in groups: Street, Number and Additional Information.
For example: address = Test Str. 5b
-> Street: "Test Str." Number: "5", Add.: "b"
My code looks like that:
string street = "";
string number = "";
string addition = "";
//this works:
string address = "Test Str. 5b";
//this doesn't match, but I want it in the street group:
//string address = "Test Str.";
Match adressMatch = Regex.Match(address, #"(?<street>.*?\.*)\s*(?<number>[1-9][0-9]*)\s*(?<addition>.*)");
street = adressMatch.Groups["street"].Value;
number = adressMatch.Groups["number"].Value;
addition = adressMatch.Groups["addition"].Value;
That code works well for the example and most other cases.
My problem:
If the adress does not contain a number, the function fails. I tried to add *? after the number group and several other things, but then the whole string got parsed into the "addition" and "street" and "number" remain empty. But if the number is missing, I want the string to parse into "street" and "number" and "addition" shall remain empty.
Thanks in advance :)
I would do it like this: I'd match the street into the street group, then match the number - if any - into the number group, and then the rest into the addition group.
Then, if the number group does not succeed, the addition value should be moved to the number group, which can be done easily within C# code.
So, use
(?<street>.*\.)(?:\s*(?<number>[1-9][0-9]*))?\s*(?<addition>.*)
^^ ^^ ^^
See the regex demo here (note the changes: the first .*? is turned greedy, the * quantifier after \. is removed, the number group is made optional together with the \s* in front).
Then, use this logic (C# sample snippet):
string street = "";
string number = "";
string addition = "";
//string address = "Test Str. 5b"; // => Test Str. | 5 | b
string address = "Test Str. b"; // => Test Str. | b |
Match adressMatch = Regex.Match(address, #"(?<street>.*\.)(?:\s*(?<number>[1-9][0-9]*))?\s*(?<addition>.*)");
if (adressMatch.Success) {
street = adressMatch.Groups["street"].Value;
addition = adressMatch.Groups["addition"].Value;
if (adressMatch.Groups["number"].Success)
number = adressMatch.Groups["number"].Value;
else
{
number = adressMatch.Groups["addition"].Value;
addition = string.Empty;
}
}
Console.WriteLine("Street: {0}\nNumber: {1}\nAddition: {2}", street, number, addition);

How to extract address components from a string?

I have a Xamarin Forms application that uses Xamarin. Mobile on the platforms to get the current location and then ascertain the current address. The address is returned in string format with line breaks.
The address can look like this:
111 Mandurah Tce
Mandurah WA 6210
Australia
or
The Glades
222 Mandurah Tce
Mandurah WA 6210
Australia
I have this code to break it down into the street address (including number), suburb, state and postcode (not very elegant, but it works)
string[] lines = address.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
List<string> addyList = new List<string>(lines);
int count = addyList.Count;
string lineToSplit = addyList.ElementAt(count - 2);
string[] splitLine = lineToSplit.Split(null);
List<string> splitList = new List<string>(splitLine);
string streetAddress = addyList.ElementAt (count - 3).ToString ();
string postCode = splitList.ElementAt(2);
string state = splitList.ElementAt(1);
string suburb = splitList.ElementAt(0);
I would like to extract the street number, and in the previous examples this would be easy, but what is the best way to do it, taking into account the number might be Lot 111 (only need to capture the 111, not the word LOT), or 123A or 8/123 - and sometimes something like 111-113 is also returned
I know that I can use regex and look for every possible combo, but is there an elegant built-in type solution, before I go writing any more messy code (and I know that the above code isn't particularly robust)?
These simple regular expressions will account for many types of address formats, but have you considered all the possible variations, such as:
PO Box 123 suburb state post_code
Unit, Apt, Flat, Villa, Shop X Y street name
7C/94 ALISON ROAD RANDWICK NSW 2031
and that is just to get the number. You will also have to deal with all the possible types of streets such as Lane, Road, Place, Av, Parkway.
Then there are street types such as:
12 Grand Ridge Road suburb_name
This could be interpreted as street = "Grand Ridge" and suburb = "Road suburb_name", as Ridge is also a valid street type.
I have done a lot of work in this area and found the huge number of valid address patterns meant simple regexs didn't solve the problem on large amounts of data.
I ended up develpping this parser http://search.cpan.org/~kimryan/Lingua-EN-AddressParse-1.20/lib/Lingua/EN/AddressParse.pm to solve the problem. It was originally written for Australian addresses so should work well for you.
Regex can capture the parts of a match into groups. Each parentheses () defines a group.
([^\d]*)(\d*)(.*)
For "Lot 222 Mandurah Tce" this returns the following groups
Group 0: "Lot 222 Mandurah Tce" (the input string)
Group 1: "Lot "
Group 2: "222"
Group 3: " Mandurah Tce"
Explanation:
[^\d]* Any number (including 0) of any character except digits.
\d* Any number (including 0) of digits.
.* Any number (including 0) of any character.
string input = "Lot 222 Mandurah Tce";
Match match = Regex.Match(input, #"([^\d]*)(\d*)(.*)");
string beforeNumber = match.Groups[1].Value; // --> "Lot "
string number = match.Groups[2].Value; // --> "222"
string afterNumber = match.Groups[3].Value; // --> " Mandurah Tce"
If a group finds no match, match.Groups[i] will return an empty string ("") for that group.
You could check if the content starts with a number for each entry in the splitLine.
string[] splitLine = lineToSplit.Split(addresseLine);
var streetNumber = string.empty;
foreach(var s in splitLine)
{
//Get the first digit value
if (Regex.IsMatch(s, #"^\d"))
{
streetNumber = s;
break;
}
}
//Deal with empty value another way
Console.WriteLine("My streetnumber is " + s)
Yea I think you have to identify what will work.
If:
it is always in the address line and it must always start with a Digit
nothing else in that line can start with a digit (or if something else does you know which always comes in what order, ie the code below will always work if the street number is always first)
you want every contiguous character to the digit that isn't whitespace (the - and \ examples suggest that to me)
Then it could be as simple as:
var regx = new Regex(#"(?:\s|^)\d[^\s]*");
var mtch = reg.Match(addressline);
You would sort of have to sift and see if any of those assumptions are broken.

Regex masking of words that contain a digit

Trying to come up with a 'simple' regex to mask bits of text that look like they might contain account numbers.
In plain English:
any word containing a digit (or a train of such words) should be matched
leave the last 4 digits intact
replace all previous part of the matched string with four X's (xxxx)
So far
I'm using the following:
[\-0-9 ]+(?<m1>[\-0-9]{4})
replacing with
xxxx${m1}
But this misses on the last few samples below
sample data:
123456789
a123b456
a1234b5678
a1234 b5678
111 22 3333
this is a a1234 b5678 test string
Actual results
xxxx6789
a123b456
a1234b5678
a1234 b5678
xxxx3333
this is a a1234 b5678 test string
Expected results
xxxx6789
xxxxb456
xxxx5678
xxxx5678
xxxx3333
this is a xxxx5678 test string
Is such an arrangement possible with a regex replace?
I think I"m going to need some greediness and lookahead functionality, but I have zero experience in those areas.
This works for your example:
var result = Regex.Replace(
input,
#"(?<!\b\w*\d\w*)(?<m1>\s?\b\w*\d\w*)+",
m => "xxxx" + m.Value.Substring(Math.Max(0, m.Value.Length - 4)));
If you have a value like 111 2233 33, it will print xxxx3 33. If you want this to be free from spaces, you could turn the lambda into a multi-line statement that removes whitespace from the value.
To explain the regex pattern a bit, it's got a negative lookbehind, so it makes sure that the word behind it does not have a digit in it (with optional word characters around the digit). Then it's got the m1 portion, which looks for words with digits in them. The last four characters of this are grabbed via some C# code after the regex pattern resolves the rest.
I don't think that regex is the best way to solve this problem and that's why I am posting this answer. For so complex situations, building the corresponding regex is too difficult and, what is worse, its clarity and adaptability is much lower than a longer-code approach.
The code below these lines delivers the exact functionality you are after, it is clear enough and can be easily extended.
string input = "this is a a1234 b5678 test string";
string output = "";
string[] temp = input.Trim().Split(' ');
bool previousNum = false;
string tempOutput = "";
foreach (string word in temp)
{
if (word.ToCharArray().Where(x => char.IsDigit(x)).Count() > 0)
{
previousNum = true;
tempOutput = tempOutput + word;
}
else
{
if (previousNum)
{
if (tempOutput.Length >= 4) tempOutput = "xxxx" + tempOutput.Substring(tempOutput.Length - 4, 4);
output = output + " " + tempOutput;
previousNum = false;
}
output = output + " " + word;
}
}
if (previousNum)
{
if (tempOutput.Length >= 4) tempOutput = "xxxx" + tempOutput.Substring(tempOutput.Length - 4, 4);
output = output + " " + tempOutput;
previousNum = false;
}
Have you tried this:
.*(?<m1>[\d]{4})(?<m2>.*)
with replacement
xxxx${m1}${m2}
This produces
xxxx6789
xxxx5678
xxxx5678
xxxx3333
xxxx5678 test string
You are not going to get 'a123b456' to match ... until 'b' becomes a number. ;-)
Here is my really quick attempt:
(\s|^)([a-z]*\d+[a-z,0-9]+\s)+
This will select all of those test cases. Now as for C# code, you'll need to check each match to see if there is a space at the beginning or end of the match sequence (e.g., the last example will have the space before and after selected)
here is the C# code to do the replace:
var redacted = Regex.Replace(record, #"(\s|^)([a-z]*\d+[a-z,0-9]+\s)+",
match => "xxxx" /*new String("x",match.Value.Length - 4)*/ +
match.Value.Substring(Math.Max(0, match.Value.Length - 4)));

Regex pattern for house letter

Im' looking for a Regex pattern that finds a house letter.
Eks(looking for the letter d).
1. Streetname 3d, 7000 Town Country.
2. Streetname 3 d, 7000 Town Country.
3. Streetname 13d, 7000 Town Country.
4. Streetname 13 d, 7000 Town Country.
I'm writing i C#.
Some combination of:
const string address = "Streetname 3d, 7000 Town Country";
string streetPart = address.Split(',')[0];
char letter = streetPart[streetPart.Length - 1];
bool isLetter = char.IsLetter(letter);
Debug.WriteLine("{0}, isLetter: {1}", letter, isLetter);
will probably work...
Outputs: d, isLetter: true
I think this pattern works in your 4 cases.
I don't test the code but just try it and tell me.
string sPattern = "[a-zA-Z 0-9]*([a-zA-Z]),.*";
int i = 0;
foreach (string s in address)
{
Match m = Regex.Match(s, sPattern);
if (m.Success){
houseLetter[i] = m.ToString();
} else {
houseLetter[i] = "Not Found";
}
i++;
}
If you are thinking that there is a regex that will universally solve this problem, stop thinking it. With your scheme my parents' street address would be
Ioakim 3rd 4242, 7000 Town Country // "Ioakim 3rd" is the street name
As you see, you are definitely going to have some percentage of wrong results. Are your four examples the only cases where you need guaranteed correct results?

Categories

Resources