


Comment valider JSON avec une expression régulière dans Golang ?
Jun 04, 2024 am 11:02 AM如何在 Go 中使用正则表达式验证 JSON?定义正则表达式模式,确保字符串以花括号开头,包含键值对,键用引号括起,值可以是字符串、数组或嵌套对象。使用正则表达式包编译正则表达式。检查 JSON 字符串是否匹配正则表达式模式。
如何在 Golang 中用正则表达式验证 JSON
正则表达式 (Regex) 是一种强大的工具,可用于验证数据的模式和结构。在 Golang 中,我们可以使用正则表达式来验证 JSON 字符串是否符合预期的格式。
正则表达式模式:
^\{(?:"[^"]+":(?:(?!\{|\[)[^\[\]\{\}\"]+|\[.+\]|\{.+\}))*\}$
分解正则表达式:
^
: 起始锚定符号,确保字符串从开头开始匹配模式。\{
: 匹配花括号打开符号 ({
))。(?:"[^"]+":(?:(?!\{|\[)[^\[\]\{\}\"]+|\[.+\]|\{.+\}))*
: 匹配键值对,其中:(?:"[^"]+":)
: 匹配冒号前面的带引号的键。(?:(?!\{|\[)[^\[\]\{\}\"]+|\[.+\]|\{.+\})
: 匹配键值对的值,可以是字符串、数组或嵌套对象。
*
: 匹配前面的元素零次或多次。\}$
:匹配花括号关闭符号 (}
).
实战案例:
考虑以下 JSON 字符串:
{ "name": "John Doe", "age": 30, "hobbies": ["reading", "playing video games"] }
要使用正则表达式验证此字符串,我们可以使用以下代码:
package main import ( "fmt" "regexp" ) func main() { // 定义正则表达式字符串 jsonRegex := "^\\{(?:\"[^\"]+\":(?:(?!\\{|\\[)[^\\[\\]\\{\\}\\\"]+|\\\\\\[.+\\]|\\\\\\[.+\\]))*}\\}$" // 编译正则表达式 regex := regexp.MustCompile(jsonRegex) // JSON 字符串 jsonString := `{ "name": "John Doe", "age": 30, "hobbies": ["reading", "playing video games"] }` // 检查字符串是否符合模式 matched := regex.MatchString(jsonString) if matched { fmt.Println("The JSON string is valid.") } else { fmt.Println("The JSON string is invalid.") } }
运行此程序将输出:
The JSON string is valid.
这表明 JSON 字符串与预期的正则表达式模式匹配,因此是有效的 JSON。
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Article chaud

Outils chauds Tags

Article chaud

Tags d'article chaud

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds

Expressions régulières PHP : correspondance exacte et exclusion des inclusions floues

Validation des expressions régulières PHP : détection du format numérique

Comment valider une adresse e-mail dans Golang à l'aide d'une expression régulière ?

Maîtriser les expressions régulières et le traitement des chaînes en langage Go

Comment faire correspondre les horodatages à l'aide d'expressions régulières dans Go ?

Comment vérifier le mot de passe à l'aide d'une expression régulière dans Go ?

Quels sont les caractères génériques des expressions régulières ?

Pourquoi ne pas utiliser l'analyse d'expressions régulières ?
