Java正则表达式value.split(" \\。"),“反斜杠点”"按性格划分? [英] Java regular expression value.split("\\."), "the back slash dot" divides by character?

查看:277
本文介绍了Java正则表达式value.split(" \\。"),“反斜杠点”"按性格划分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的理解,反斜杠点( \。)表示任何字符的一个字符?因为反斜杠是一个转义,它应该是反斜杠反斜杠点(\\。

From what I understand, the backslash dot (\.) means one character of any character? So because backslash is an escape, it should be backslash backslash dot ("\\.")

这对字符串有什么作用?我刚刚在我正在处理的现有代码中看到了这一点。据我所知,它会将字符串拆分为单个字符。为什么这样做而不是 String.toCharArray()。那么这会将字符串拆分为一个字符串数组,该数组只包含数组中每个字符串的一个字符?

What does this do to a string? I just saw this in an existing code I am working on. From what I understand, it will split the string into individual characters. Why do this instead of String.toCharArray(). So this splits the string to an array of string which contains only one char for each string in the array?

推荐答案

我的猜测是您缺少反斜杠('\')字符是Java字符串文字中的转义字符。因此,当您想在编写为Java String的正则表达式中使用'\'转义时,您需要将其转义;例如。

My guess is that you are missing that backslash ('\') characters are escape characters in Java String literals. So when you want to use a '\' escape in a regex written as a Java String you need to escape it; e.g.

Pattern.compile("\.");   // Java syntax error

// A regex that matches a (any) character
Pattern.compile(".");  

// A regex that matches a literal '.' character
Pattern.compile("\\.");  

// A regex that matches a literal '\' followed by one character
Pattern.compile("\\\\.");

String.split(String separatorRegex)方法将String拆分为由与正则表达式匹配的子字符串分隔的子字符串。所以 str.split(\\。)会将 str 拆分为由单个文字分隔的子字符串' ''字符。

The String.split(String separatorRegex) method splits a String into substrings separated by substrings matching the regex. So str.split("\\.") will split str into substrings separated by a single literal '.' character.

这篇关于Java正则表达式value.split(" \\。"),“反斜杠点”"按性格划分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆