I'm using typescript langage. I need to extract currency sign out of balance money, for example from "£1,070,449.00" I need "£" only. There are other currencies too, some of which are added at start of value like "£1,700" or some are appended at the end of value like "1,070,449.00 kr". I also have value 10070449 in a variable.
Summarising, I have:
parent1 = £1,070,449.00
child1 = 10070449
requirement1 = £
parent2 = 1,070,449.00 kr
child2 = 10070449
requirement2 = kr
# python
from re import sub
from decimal import Decimal
money = '$6,150,593.22'
value = Decimal(sub(r'[^\d.]', '', money))
currency_sign = sub(r'[\d.,]', '', money)
print(value)
print(currency_sign)
and this is output:
6150593.22
$
the kr one also works, you can modify this to meet you needs.
I am sorry I didn't notice it is typescript, but the regex is language independent, so it is not too much different.
what we need to do is to remove the digit, ',' and '.' from the string.
var money = '$6,150,593.22'
var pattern = /[\d.,]/g;
console.log(money.replace(pattern, ""))
and the output is:
$
Related
import re
s = 'so the 1234 2-1-1919 215.777.9839 1333331234 20-20-2000 A1234567 (515)2331129 7654321B (511)231-1134 512-333-1134 7777777 a7727373 there 1-22-2001 *1831 5647 and !2783 '
reg = r'[()\d-]{7,}'
r1 = re.findall(reg,s)
I have the following reg that gives the following
r1
['2-1-1919',
'1333331234',
'20-20-2000',
'1234567',
'(515)2331129',
'7654321',
'(511)231-1134',
'512-333-1134',
'7777777',
'7727373',
'1-22-2001']
I want to get the following output
['(515)2331129',
'(511)231-1134',
'512-333-1134']
So I tried to alter reg = r'[()\d-]{7,}' by adding \b
reg = r'[\b()\b\d-]{7,}'
But this doesnt work. How do I change reg = r'[()\d-]{7,}' to get the output I want?
To put my two cents in, you could use a regex/parser combination as in:
from parsimonious.grammar import Grammar
from parsimonious.expressions import IncompleteParseError, ParseError
import re
junk = """so the 1234 2-1-1919 215.777.9839 1333331234 20-20-2000 A1234567 (515)2331129 7654321B
(511)231-1134 512-333-1134 7777777 a7727373 there 1-22-2001 *1831 5647 and !2783"""
rx = re.compile(r'[-()\d]+')
grammar = Grammar(
r"""
phone = area part part
area = (lpar digits rpar) / digits
part = dash? digits
lpar = "("
rpar = ")"
dash = "-"
digits = ~"\d{3,4}"
"""
)
for match in rx.finditer(junk):
possible_number = match.group(0)
try:
tree = grammar.parse(possible_number)
print(possible_number)
except (ParseError, IncompleteParseError):
pass
This yields
(515)2331129
(511)231-1134
512-333-1134
The idea here is to first match possible candidates which are then checked with the parser grammar.
Maybe, we could use alternation based on the cases you might have:
\d{3}-\d{3}-\d{4}|\(\s*\d{3}\s*\)\d{7}|\(\s*\d{3}\s*\)\s*\d{3}-\d{4}
We can also include additional boundaries if it'd be necessary:
(?<!\S)(?:\d{3}-\d{3}-\d{4}|\(\s*\d{3}\s*\)\d{7}|\(\s*\d{3}\s*\)\s*\d{3}-\d{4})(?!\S)
Demo
Test
import re
expression = r"\d{3}-\d{3}-\d{4}|\(\s*\d{3}\s*\)\d{7}|\(\s*\d{3}\s*\)\s*\d{3}-\d{4}"
string = """
so the 1234 2-1-1919 215.777.9839 1333331234 20-20-2000 A1234567 (515)2331129 7654321B (511)231-1134 512-333-1134 7777777 a7727373 there 1-22-2001 *1831 5647 and !2783 (511) 231-1134 ( 511)231-1134 (511 ) 231-1134
511-2311134
"""
print(re.findall(expression, string))
Output
['(515)2331129', '(511)231-1134', '512-333-1134', '(511) 231-1134', '( 511)231-1134', '(511 ) 231-1134']
If you wish to explore/simplify/modify the expression, it's been
explained on the top right panel of
regex101.com. If you'd like, you
can also watch in this
link, how it would match
against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
This is my code:
$db = new COM("ADODB.Connection");
$dsn = "DRIVER={SQL Server}; SERVER={$server}; UID={$usr}; PWD={$pwd}; DATABASE={$dbname}";
$db->Open($dsn);
$sql = "SELECT o.CardCode, o.CardName, o.VatIDNum, o.AddID, o.Cellular, o.E_Mail, c.Address
FROM ocrd o INNER JOIN crd1 c ON o.CardCode = c.CardCode
WHERE o.Cellular = '$phone1' o.CardName LIKE N'%$lname%'";
$result = $db->execute($sql);
In the databese the o.Cellular column includes phone numbers that could be formatted with dashes/spaces/+ sign/braces so when I am checking WHERE o.Cellular = '$phone1' I need to reformat o.Cellular to only digits (the $phone1 already only digits).
The second problem is that if o.Cellular not equals $phone1, I want to check o.CardName LIKE N'%$lname%'.
So the current part of code doesn't works as I need.
Any help please...
REGEX is extremely limited in SQL Server. Here's an example to replace the following characters in your phone number: + ( ) - \s
SELECT
o.CardCode,
o.CardName,
o.VatIDNum,
o.AddID,
o.Cellular,
o.E_Mail,
c.Address
FROM
ocrd o
INNER JOIN
crd1 c ON
o.CardCode = c.CardCode
WHERE
replace(replace(replace(replace(replace(o.Cellular,'-',''),' ',''),'(',''),')',''),'+','') = '$phone1'
or o.CardName LIKE N'%$lname%'
--test example you can run to see the results of the code
declare #Cellular varchar(16) = '+1 (156) 555-7899'
select replace(replace(replace(replace(replace(#Cellular,'-',''),' ',''),'(',''),')',''),'+','')
--returns 1156555789
My own final solution:
$phone1 = "0123456789"; /* tests 0123456789 */
$phone1 = preg_replace("/\D+/", "", $phone); /* Leave digits only */
$phone1_wildcard = "%".implode("%",str_split($phone1))."%"; /* converts 0123456789 to %0%1%2%3%4%5%6%7%8%9% in order to catch any mistyping in mssql */
Regex isn't my strongest point. Let's say I need a custom parser for strings which strips the string of any letters and multiple decimal points and alphabets.
For example, input string is "--1-2.3-gf5.47", the parser would return
"-12.3547".
I could only come up with variations of this :
string.replaceAll("[^(\\-?)(\\.?)(\\d+)]", "")
which removes the alphabets but retains everything else. Any pointers?
More examples:
Input: -34.le.78-90
Output: -34.7890
Input: df56hfp.78
Output: 56.78
Some rules:
Consider only the first negative sign before the first number, everything else can be ignored.
I'm trying to do this using Java.
Assume the -ve sign, if there is one, will always occur before the
decimal point.
Just tested this on ideone and it seemed to work. The comments should explain the code well enough. You can copy/paste this into Ideone.com and test it if you'd like.
It might be possible to write a single regex pattern for it, but you're probably better off implementing something simpler/more readable like below.
The three examples you gave prints out:
--1-2.3-gf5.47 -> -12.3547
-34.le.78-90 -> -34.7890
df56hfp.78 -> 56.78
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(strip_and_parse("--1-2.3-gf5.47"));
System.out.println(strip_and_parse("-34.le.78-90"));
System.out.println(strip_and_parse("df56hfp.78"));
}
public static String strip_and_parse(String input)
{
//remove anything not a period or digit (including hyphens) for output string
String output = input.replaceAll("[^\\.\\d]", "");
//add a hyphen to the beginning of 'out' if the original string started with one
if (input.startsWith("-"))
{
output = "-" + output;
}
//if the string contains a decimal point, remove all but the first one by splitting
//the output string into two strings and removing all the decimal points from the
//second half
if (output.indexOf(".") != -1)
{
output = output.substring(0, output.indexOf(".") + 1)
+ output.substring(output.indexOf(".") + 1, output.length()).replaceAll("[^\\d]", "");
}
return output;
}
}
In terms of regex, the secondary, tertiary, etc., decimals seem tough to remove. However, this one should remove the additional dashes and alphas: (?<=.)-|[a-zA-Z]. (Hopefully the syntax is the same in Java; this is a Python regex but my understanding is that the language is relatively uniform).
That being said, it seems like you could just run a pretty short "finite state machine"-type piece of code to scan the string and rebuild the reduced string yourself like this:
a = "--1-2.3-gf5.47"
new_a = ""
dash = False
dot = False
nums = '0123456789'
for char in a:
if char in nums:
new_a = new_a + char # record a match to nums
dash = True # since we saw a number first, turn on the dash flag, we won't use any dashes from now on
elif char == '-' and not dash:
new_a = new_a + char # if we see a dash and haven't seen anything else yet, we append it
dash = True # activate the flag
elif char == '.' and not dot:
new_a = new_a + char # take the first dot
dot = True # put up the dot flag
(Again, sorry for the syntax, I think you need some curly backets around the statements vs. Python's indentation only style)
I was trying to have the value as 456,987,214.
But For me it is coming like without comma.
Here is my code, Did i mistake anything
const string price = "^\\d{3},\\d{3},\\d{3}$";
string pricelist = query.price.ToString();
string price1 = "";
if (System.Text.RegularExpressions.Regex.IsMatch(pricelist.ToString(), price))
{
price1 = query.price.ToString();
}
I noticed it, it is number what you intended to format why not using angular built-in formatting feature like: {{price | number}}
Online Demo
If you want to format this with C# then you can format it using .Net built-in formatters like:
double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
// outputs 1,234,567,890
Try this simple Method:
Just pass your value like this ,
double value = double.Parse(query.price.ToString());
string price1= value.ToString("#,#", CultureInfo.InvariantCulture);
Output will be like 123,456,789
Try this simple method: Just pass your value like this, then you will get the output as you want.
double value = double.Parse(query.price.ToString());
string price1= value.ToString("#,#", CultureInfo.InvariantCulture);
Output will be like 123,456,789
I'm making a program that scrambles words for fun and I've hit a roadblock. I am attempting to switch all the letters in a string and I'm not quite sure how to go about it (hello = ifmmp). I've looked all around and haven't been able to find any answers to this specific question. Any help would be great!
You want a simple randomized cypher? The following will work for all lowercase inputs, and can easily be extended.
import random
import string
swapped = list(string.lowercase)
random.shuffle(swapped)
cipher = string.maketrans(string.lowercase, ''.join(swapped))
def change(val):
return string.translate(val, cipher)
You can probably modify this example to achieve what you need. Here every vowel in a string is replaced by its vowel position:
from string import maketrans # Required to call maketrans function.
intab = "aeiou"
outtab = "12345"
trantab = maketrans(intab, outtab)
str = "this is string example....wow!!!";
print str.translate(trantab);
# this is the output
"th3s 3s str3ng 2x1mpl2....w4w!!!"
Try maketrans in combination with the string.translate function. This code removes letters from your word from the letters you are scrambling with first. If you just want lowercase only use string.lowercase instead of string.letters.
>>> import string, random
>>> letters = list(string.letters)
>>> random.shuffle(letters)
>>> letters = "".join(letters)
>>> word = 'hello'
>>> for letter in word:
... letters = letters.replace(letter, '')
...
>>> transtab = string.maketrans(word, letters[:len(word)])
>>> print word.translate(transtab)
XQEEN
The "scrambling" you appear to be after is called Caesar's cipher, with a right shift of 1. The following Python will achieve what you're after:
def caesar(str):
from string import maketrans
fromalpha = "abcdefghijklmnopqrstuvwxyz"
# Move the last 1 chars to the start of the string
toalpha = fromalpha[1:] + fromalpha[:1]
# Make it work with capital letters
fromalpha += fromalpha.upper()
toalpha += toalpha.upper()
x = maketrans(fromalpha, toalpha)
return str.translate(x)
If you're interested in the general case, this function will do the job. (Note that it is conventional to express Caesar ciphers in terms of left shifts, rather than right.)
def caesar(str, lshift):
from string import maketrans
fromalpha = "abcdefghijklmnopqrstuvwxyz"
toalpha = fromalpha[-lshift:] + fromalpha[:-lshift]
fromalpha += fromalpha.upper()
toalpha += toalpha.upper()
x = maketrans(fromalpha, toalpha)
return str.translate(x)