In this Java regex tutorial, we will learn to match all available currency symbols, e.g. $ Dollar, € Euro, ¥ Yen, in some text content or a String in Java.
1. Regex for Currency Symbols
In regular expressions, the property\Sc
represents the currency symbols. We can use the \\p{Sc}
to match all currency symbols in the string.
\\p{Sc}
Note that \p{Sc}
is PCRE regex property and Javascript doesn’t support it.
is PCRE regex property and Javascript doesn’t support it. In Javascript you need to use specific symbols in character class to match them like this:
\p{Sc}
/[$£]/
2. Example
In the following program, we have a test string that contains the 3 currency symbols. We will use the above-discussed regular expression to match the currency symbols, and then print their locations in the string.
String content = "Let's find the symbols or currencies : $ Dollar, € Euro, ¥ Yen";
String regex = "\\p{Sc}";
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(content);
while (matcher.find())
{
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(" : " + matcher.group());
}
The program output:
Start index: 39 End index: 40 : $
Start index: 49 End index: 50 : €
Start index: 57 End index: 58 : ¥
Happy Learning !!
Comments