C# Regex Match Address - Mark groups optional - c#

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);

Related

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

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;

How to split a street address after the first number?

I'm not sure how to solve this but I need to split a string into 2 parts. Take the string below for example:
North Street 57A 1floor
I need to split this into 2 parts.
Part 1 "North Street 57" and part 2 "A 1floor"
But if the address is just "North Street 57" then I don't need to split the string at all, so the key here is to identify if the first occurrence of street number is only digits or a combination of digits and characters (57A)
I have a lot of different address names so the text can vary. Can this be achieved?
If you always want to split after the first occurrence of a number, you may use Regular Expression for that.
Here's a full example:
string input = "North Street 57A 1floor";
var regex = new Regex(#"(?<=\d)(?=\D)");
var parts = regex.Split(input, 2);
foreach (var part in parts)
Console.WriteLine(part);
Output:
North Street 57
A 1floor
The pattern (?<=\d)(?=\D) gets the position after a string of digits. Then, we use Regex.Split(string input, int count) where count=2 to ensure that it returns two parts at maximum.
Try it online.

Split by period ignore few cases

I am splitting a string with a period and space(". "), I want to split with a ". " but ignore if it matches few patterns like MR. , JR. , [oneletter]. , Dr.
Pattern list is static.(case insensitive)
Examples:
1) My Name is MR. ABC and working for XYZ.
Output: No split. Just one line
2) My Name is Mr. ABC. I work for XYZ.
Output: string[0] = My Name is Mr. ABC.
string[1] = I work for XYZ.
3) My Name is ABC. I work for XYZ.
Output: string[0] = My Name is ABC.
string[1] = I work for XYZ.
4) My Name is MR. ABC Jr. DEF. I work for XYZ.
Output: string[0] = My Name is MR. ABC Jr. DEF. (MR. and Jr. are ignoring cases )
string[1] = I work for XYZ.
Using sln's regex pattern here's a mock up of how it should work
List<string> ignores = new List<string>(){ "MR", "MS", "MRS", "DR", "PROF" };
ignores = ignores.Select(x => #"\b" + x).ToList();
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
foreach (char letter in alphabet.ToCharArray())
{
ignores.Add(#"\b" + letter);
}
string test = "This is a test for Prof. Plum. Here is a test for Ms. White. This is A. Test. Welcome to GMR. Next Line.";
string regexPattern = $#"(?<!{string.Join("|", ignores)})\.\s";
string[] results = Regex.Split(test, regexPattern, RegexOptions.IgnoreCase);
results are the 3 sentences (though you need to re-add the . to the end of all but the last value)
Edited to add all single character ignores
Edited to only account for whole words on ignore list

c# Regex - Only get numbers and whitespaces in one string and only text and whitespaces in another

How do I only get numbers and include whitespaces in one string and only text and white spaces in another?
Iv'e tried this:
string value1 = "123 45 New York";
string result1 = Regex.Match(value1, #"^[\w\s]*$").Value;
string value2 = "123 45 New York";
string result2 = Regex.Match(value2, #"^[\w\s]*$").Value;
result1 need to be "123 45"
result2 need to be " New York"
Try next code:
string value1 = "123 45 New York";
string digitsAndSpaces = Regex.Match(value1, #"([0-9 ]+)").Value;
string value2 = "123 45 New York";
string lettersAndSpaces = Regex.Match(value2, #"([A-Za-z ])+([A-Za-z ]+)").Value;
Update:
How do I allow charachters like å ä ö in result from value2?
string value3 = "å ä ö";
string speclettersAndSpaces = Regex.Match(value3, #"([a-zÀ-ÿ ])+([a-zÀ-ÿ ]+)").Value;
The fallowing regex will allow only digits and spaces between them, the same goes with characters.
Regex: (?:\d[0-9 ]*\d)|(?:[A-Za-z][A-Za-z ]*[A-Za-z])
Details:
(?:) Non-capturing group
\d matches a digit (equal to [0-9])
[] Match a single character present in the list
* Matches between zero and unlimited times
| or
Output:
Match 1
Full match 0-6 `123 45`
Match 2
Full match 7-15 `New York`
Regex demo

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.

Categories

Resources